Question

I'm working on an application implementing MVVM light. The application is network-based and can receive data at any time which will change values in the Model.

What is the recommended method in MVVM light for notifying ViewModels that data in the Model has changed (from an event which was not triggered by the View or ViewModel) and that the View should be updated?

Était-ce utile?

La solution

I will be abstract from MVVM Light and try to show a universal solution that will fit the style of MVVM.


Notifying ViewModels that data in the Model has changed

Yours properties that are in the Model or in the ViewModel must implement the INotifyPropertyChanged interface. He has an event PropertyChangedEventHandler(propertyName) which informs on notification properties:

public class NotificationObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Suppose, we have this interface which implements a Model:

public class MyModel : NotificationObject
{
    private string _text = "";

    public string Text
    {
        get
        {
            return _text;
        }

        set
        {
            _text = value;
            NotifyPropertyChanged("Text");
        }
    }
}

Then, to know when this property is changed, create an event handler for ViewModel in constructor:

public MyViewModel() 
{
    MyModel = new MyModel();        
    MyModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MyModel_PropertyChanged);
}

private void MyModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if (e.PropertyName.Equals("Text")) 
    {
        System.Diagnostics.Debug.WriteLine("Text changed");
    }            
}

From an event which was not triggered by the View or ViewModel

If this event did not happen in the View or in the ViewModel, then how to work with him in the style of MVVM? In the Model, this event exactly shall not triggered as is should only properties and maximum realization of INotifyPropertyChanged interface.

In any case, I advise you to handle this event in the ViewModel - for him it is a good place. You should not think that these data will be updated over the network or the user, try to find the most abstract solution that does not depend on the implementation. You can create a class helper with an interface, who will work with the network and call it on the side of the ViewModel, for example in Command.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top