MVVM is a great fit for WPF development in general, not just in TreeView
s.
If Data(ItemsSource) is added, edited
or delete, how to keep the Data and
the ViewModel consistent?
Not sure exactly what you're asking here, but WPF binding handles collection changes, as long as those collection implement INotifyCollectionChanged
. ObservableCollection<T>
gives you a nice, useful implementation of this interface that you can use within your view models.
Bindings keep the view consistent with your view model. Generally what you're aiming for is zero code-behind in your view. Your view just binds to properties on the view model and it is the responsibility of the view model to keep related properties in sync. Here's a really simple example:
public class PersonViewModel : INotifyPropertyChanged
{
public string FirstName
{
get { return _firstName; }
set
{
if (_firstName != value)
{
_firstName = value;
OnPropertyChanged("FirstName");
OnPropertyChanged("FullName");
}
}
}
//LastName and other members omitted
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
Here the FullName
property is affected by changes to FirstName
and LastName
. The view can just bind to FullName
and any changes to the other two properties will be visible in the UI.
I'd advise you to read my blog post on POCOs versus DependencyObject
s as view models before you start out.
HTH,
Kent