简体   繁体   中英

Simple usercontrol and MVVM pattern: How to use?

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

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...

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.

if you wanna create real usercontrols you should not:

 DataContext = this;

here a quote from HB

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM