简体   繁体   中英

MVVM: Updating ViewModel properties based on Model properties

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?

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.

由于您不想将依赖关系放在模型内部的视图模型上,因此侦听视图模型中的模型更改确实是更新基于模型的视图模型属性的正确方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM