Wpf – Binding an IList to list control using MVVM

data-bindingilistmvvmwpf

I am trying to understand MVVM pattern and I took a sample program to work on. The model is a C# .net library which when queried returns an IList<INote> object. I want my view to be able to add/edit/delete items in this collection through data binding. But I don't know how to start with this, using MVVM. Please help me out.

Model exposes an interface to retrieve the IList<INote> objecs,
View has a list box showing the contents of IList<INote> and couple of other controls to add data to the IList<INote>.

Best Answer

Bind your ListBox to an ObservableCollection<T> and it will instantly be updated everytime you add or remove something from that ObservableCollection<T>.

This ObservableCollection<T> should normally be a property of your ViewModel.

If the IList property from your Model is not observable (and you don't have control over it), you will have to write the code to synchronize it within your ViewModel. These are questions of architecture then. I feel the cleanest choice in this regard is to actually use a ReadOnlyObservableCollection<T> and add / remove items using your repository and synchronize accordingly.

Related Topic