WPF User Control hell with MVVM and Dependency Properties

前端 未结 4 526
醉酒成梦
醉酒成梦 2020-12-09 10:41

This is what I\'m trying to do:

  • I\'m writing a UserControl that I want to be consumed by other developers.
  • I want end users to be able

4条回答
  •  遥遥无期
    2020-12-09 11:10

    Basically, instead of binding your UserControl's datacontext to the userControlViewModel, it's better to do it on the first child element of the user control. That way, all the references that you make within the control will be bound to the userControlViewModel, but the dependencies properties can be set from the data context set where you want to use your UserControl.

    This is from a project I'm working at:

    
    
        
            {Binding SomethingInMyUserControlViewModel}
        
    
    

    Then on the code behind:

    public partial class MyUserControl : UserControl
    {
        UserControlViewModel _vm;
    
        public MyUserControl()
        {
            InitializeComponent();
    
            //internal viewModel set to the first child of MyUserControl
             rootDock.DataContext = new UserControlViewModel();
    
            _vm = (UserControlViewModel)rootDock.DataContext;
    
    
            //sets control to be able to use the viewmodel elements
    
         }
    
         #region Dependency properties 
         public string textSetFromApplication
         {
             get{return (string)GetValue(textSetFromApplicationProperty);}
             set{SetValue(textSetFromApplicationProperty, value);}
         }
    
         public static readonly DependencyProperty textSetFromApplicationProperty = DependencyProperty.Register("textSetFromApplication", typeof(string), typeof(MyUserControl), new PropertyMetadata(null, OnDependencyPropertyChanged));
    
         private static void  OnDependencyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
         {
            ((MyUserControl)d)._vm.SomethingInMyUserControlViewModel = 
                 e.NewValue as string;
         }
    #endregion
    

    Then when you use this on your main view, you can set the dependency property with the value you want to pass to MyUSerControl

提交回复
热议问题