MVVM: Updating ViewModel properties based on Model properties

566 views Asked by At

I have some properties in ViewModel that are updated/recalculated based on Model Properties updates. I am asking for the best approach to implement this scenario?

I don't like the approach of subscribing to PropertyChanged Event Handler of Model and then updating ViewModel properties. How do you handle this scenario?

2

There are 2 answers

1
ManOVision On

Subscribing to events is the right approach, but I agree with you about not wanting to use the PropertyChanged event. I like to leave that event alone and create my own events as needed. Here is my approach:

public class Person : INotifyPropertyChanged
{
    //custom events as needed
    public event EventHandler NameChanged = delegate { };

    //needed for INotifyPropertyChanged 
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                this.NotifyPropertyChanged();

                //Fire my custom event
                this.NameChanged(this, EventArgs.Empty);
            }
        }
    }

    private int _age;
    public int Age
    {
        get { return _age; }
        set
        {
            if (_age != value)
            {
                _age = value;
                this.NotifyPropertyChanged();

                //I am not exposing a custom event for this property.
            }
        }

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

In this example, Name and Age are observable for UI purposes, but Name is observable to anything outside of the UI. Now if you remove any PropertyChanged notifications, you don't accidentally cause that runtime error if your ViewModel was subscribed to PropertyChanged and parsing the string.

0
poke On

Since you don’t want to put the dependency on the view model inside the model, listening to model changes in the view model is indeed the right approach to update view model properties that are based on the model.