Say you have a ViewModel class, with a property named 'customers' which is a list of customers. 3 things can be changed:
- The customer property in your view model (i.e. you change the entire list with: this.customers = new list
- You add or remove items to or from the list.
- A change in a property of a specific customer already in the list (e.g. customers[0].address = 'xxx';
WPF Binding mechanism can handle all cases, provided you fire the correct events. Depends on your scenario each case that can happen has to be handled.
Work around #1 simply by saying that your collection of customer cannot be changed. That is, you allocate the list of customers during the construction of your ViewModel, and you don't replace this property.
For #2, best thing is to reuse a .NET object named ObservableCollection. This collection implements INotifyPropertyChanged, and fires the correct notification with the correct argument upon calls to Add, Remove, Clear, etc.
For #3, you need to implement INotifyPropertyChanged for your Customer object. For example:
public class Customer : INotifyPropertyChanged
{
public PropertyChangedEventHandler PropertyChanged;
private string _name;
public string name {
get { return _name; }
set { _name = value; ... /* add code to fire exception */ }
}
... // more properties
}
Now, in your view model, have an observable collection
public class ViewModel
{
public ObservableCollection<Customer> customers { get; private set; }
ViewModel( ) {
// Allocate it once during construction
customers = new Observablecollection<Customer>( )
}
}
In the UI, you just need to bind. Whatever ItemsControl you are using:
<ItemsControl DataSource="{Binding customers}">
<!-- The template to display the items here -->
</ItemControl>
Now, you just need to keep in sync the customers collection with the one on the server. Any change you do to customer will be reflected in the UI.