Question

I am currently away from home (and will be for a few more weeks) and only have a tablet - therefore, I have no access to Visual Studio to test what I'm trying to learn - the MVVM pattern.

So far, I think the theory is set, but I'm confused about the INotifyPropertyChanged interface.

I think one of the ideas of the MVVM pattern is to be able to update the Model which in turn notifies the ViewModel which in turn notifies the view. If I'm wrong then the rest of this question is meaningless.

My question is, do all the classes have to share 1 implementation of INotifyPropertyChanged?

In other words, which is correct:

  1. A property name is the same for all classes (but each class has it's own unique implementation of INotifyPropertyChanged)

  2. A property name is the same for all classes (and each class inherits from a single base class which implements INotifyPropertyChanged)?

Was it helpful?

Solution

No, they don't have to share anything. However the implementation of INotifyPropertyChanged is some lines of code, so we usually made a base class for models - like BaseModel or BaseViewModel which implemented INotifyPropertyChanged.

The implementations are generally specific to the version of C# language you use (the older ones works in the newer version of language).

Look here: http://jesseliberty.com/2012/06/28/c-5making-inotifypropertychanged-easier/

but instead of having the Employee class to implement the INotifyPropertyChanged, you can implement it in a base class

public class BaseViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged([CallerMemberName] string caller = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
        }
    }
}

and then the Employee class from the blog should look like this

public class Employee : BaseViewModel
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged();
        }
    }
}

this is for C# 5 (the .Net 4.5 - the one which does not run on Windows XP)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top