Simple usercontrol and MVVM pattern: How to use?

白昼怎懂夜的黑 提交于 2019-12-25 05:21:38

问题


Please help me

I have

public partial class OrderControl : UserControl
{
    private OrderHeader orderHeader;
    public Customer selectedCustomer { get; set; }
    private Customer[] allCustomers;
    public User selectedManager { get; set; }
    private User[] allManagers;


    public OrderControl()
    {
        InitializeComponent();
        DataContext = this;
    }
...
}

And I need one way binding to source:

<ComboBox Name="CustomerComboBox" SelectedItem="{Binding selectedCustomer}"/>

Is this best way to keep selectedCustomer Property in OrderControl.xaml.cs or I need to create some OrderViewModel class with ..,selectedCustomer,... Properties and keep an instance of OrderViewModel in OrderControl.xaml.cs?

thanks


回答1:


That will work if you implement INotifyPropertyChanged. Right now there is no way for the combobox to get updates when the property is set. See http://msdn.microsoft.com/en-us/library/ms229614.aspx

However, if you wish to follow MVVM, then you will want to create a view model object.




回答2:


It is best to create a ViewModel class, move your properties to that class and make it a DataContext of your UserControl.

Also, your selectedCustomer property is just a regular .NET property and it needs to support INotifyPropertyChanged interface in order to facilitate binding and change notification... typically a base ViewModel class from which all your other ViewModel classes inherit would implement this interface...




回答3:


if you wanna create real usercontrols you should not:

 DataContext = this;

here a quote from H.B.

It's bad practice, setting the DataContext like that is invisible "from the outside" and impractical as inheritance of the DataContext is usually what you want and expect

here is are similar question and answer.

but if you wanna do MVVM with viewmodel first.

quote from Rachel:

Remember, with MVVM your ViewModels are your application. The View is just a pretty interface that allows users to interact with your ViewModels.

that mean you should create appropriate viewmodels with all properties and commands you need. remove all code from your usercontrol because its now just a view. viewmodel first connects the viewmodel and the view through datatemplates.



来源:https://stackoverflow.com/questions/11566632/simple-usercontrol-and-mvvm-pattern-how-to-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!