views:

103

answers:

1

A part of the editor i'm writing uses a Wpf-TreeView. I'm using DataBinding and an ItemTemplate to populate the TreeView. So far i'm manipulating the ItemsSource(mostly ObeservableCollection's) dircetly(using for example Drag&Drop). But now i read this and i'm not sure if it would realy simplify thinks for me. And before i go on with the project i whould like to know all Pros and Cons.

If Data(ItemsSource) is added, edited or delete, how to keep the Data and the ViewModel consistent? Is that something the ViewModel has to take care of? If i have to take care of the consistens how does this simplifies thinks?

+3  A: 

MVVM is a great fit for WPF development in general, not just in TreeViews.

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 DependencyObjects as view models before you start out.

HTH, Kent

Kent Boogaart
sry for my bad english. in your example, if the firstName is changed you need to update the firstname of the _person.firstName (private Person _person) rigth?
Marcel Benthin
Sure, if you have a Person class already then your PersonViewModel can wrap that class instead of having its own fields for names. However, the view model can also add its own fields that are relevant only to the UI (eg. a PersonBrush property that determines what color to use for a person's name)
Kent Boogaart