Wpf UserControl and MVVM

后端 未结 3 483
青春惊慌失措
青春惊慌失措 2020-12-13 19:30

I am thinking about writing a WPF User Control for my application. I am using MVVM in my application.

User control\'s may require Dependency Properties that can be

3条回答
  •  我在风中等你
    2020-12-13 20:22

    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 pattern has worked pretty well for me, on your UserControl XAML:

    
    
        
            {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
    

提交回复
热议问题