To implement data binding in WPF, according to MS a "class needs to provide the proper property changed notifications." [ref here]
AFAIK, part of setting this up means taking the following steps, if not already set up in the class (ref this article on MSDN):
- When properties are changed, they need call to a method to raise an event.
- This means auto-implemented properties must be changed so they use a private backing field, so
set
can change the property and also call the method to raise an event.
- This means auto-implemented properties must be changed so they use a private backing field, so
- The class needs to implement INotifyPropertyChanged.
- The class needs to declare the PropertyChangedEventHandler event.
- The event needs to be raised in something like this:
...
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
If I already have many existing classes that do not take any of these steps, what is the best way to change these classes so they change only so far as is needed to make them meet these standards?
If you want the minimum-possible-code-impact solution, then you want the Fody PropertyChanged weaver. This is installed as a NuGet package with
Install-Package PropertyChanged.Fody
, or through the VS package manager dialogue.Once installed, you can mark a class with the
[ImplementPropertyChanged]
attribute, and your job is basically done. The weaver will add the relevant event calls at compile time by manipulating the generated IL, which means that you don't have to explicitly implement the interface or the event calls in code. You can keep your auto-implemented property syntax, too!The linked docs provide details of more advanced cases but, in my experience, the out-of-box behaviour is sufficient for almost all needs.