简体   繁体   中英

Understanding INotifyPropertyChanged

When we implement INotifyPropertyChanged, what is it notifying?

Is it only notifying the View (I doubt it), or every property that has the name (That could provide unwanted affects). Or is it only the properties that exist in the DataContext (doubtful as there is possibly no DataContext in a Model)?

Would it be possible to have a single function like

public class Demo : BaseViewModel
{
    public void UpdateAll()
    {
        //Update properties which do not exist in this class
        OnPropertyChanged("NameFromClassA");
        OnPropertyChanged("NameFromClassB");
        OnPropertyChanged("AgeInClassA");
        OnPropertyChanged("AgeInClassC");
    }
}

I have tried it, but I can't get it to work. There are no binding errors in the Output window, nor any runtime/compiler issues.

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.

For example, consider a Person object with a property called FirstName. To provide generic property-change notification, the Person type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when FirstName is changed.

For change notification to occur in a binding between a bound client and a data source, your bound type should either: Implement the INotifyPropertyChanged interface (preferred). Provide a change event for each property of the bound type.

For a Sample Program check this : MSDN

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.

OnPropertyChanged("NameFromClassA") is typically implemented in the BaseViewModel Class and is equivalent to doing :

    if (this.PropertyChanged != null)
      this.PropertyChanged(this, new PropertyChangedEventArgs("NameFromClassA"));

It tells whoever is listening to the PropertyChanged event of your Demo Class that a Property named "NameFromClassA" has changed value (your example is wrong because there's no such Property in your Class ).

It's required for DependencyProperties bound to Properties of your VM to update themselves and is rarely used for anything else.


Edit:

Psoeudo-code of what's roughly equivalent to what the binding engine does behind the scene :

ClassA myClassA;
string myPropertyBoundToNameOfClassA;

// somewhere after myClassA was initialized
myClassA.PropertyChanged += OnMyClassAPropertyChanged;

void MyClassAPropertyChanged(string name)
{
   if (name == "NameFromClassA")
       myPropertyBoundToNameOfClassA = myClassA.Name;
}

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