WPF advanced development and wpf advanced development
INotifyPropertyChanged
In the development of the wpf mvvm mode, the ViewModel that implements INotifyPropertyChanged is very important and common class:
public class MainViewModel : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }}
In the class, all attributes that need to respond to changes must call the property change method in Setter:
private string _appName;public string AppName{ get { return _appName; } set { if (_appName == value) return; _appName = value; OnPropertyChanged(nameof(AppName)); }}
In this way, one or two attributes are okay. When there are many attributes, they seem complicated. Today, we want to introduce an open-source tool to solve this problem.
Fody/PropertyChanged
Open Source Address: https://github.com/Fody/PropertyChanged/
INotifyPropertyChanged code in the property during compilation
Usage
<?xml version="1.0" encoding="utf-8"?><Weavers> <PropertyChanged /></Weavers>
Description
All the classes marked with the [ImplementPropertyChanged] feature or INotifyPropertyChanged feature in the project automatically implement notification-related code in their properties, unless the property is marked as not notified
[ImplementPropertyChanged]public class Person { public string GivenNames { get; set; } public string FamilyName { get; set; } public string FullName { get { return string.Format("{0} {1}", GivenNames, FamilyName); } }}
Or
public class MainViewModel : INotifyPropertyChanged{ public string GivenNames { get; set; } public string FamilyName { get; set; } public string FullName { get { return string.Format("{0} {1}", GivenNames, FamilyName); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }}
public class Person : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged; string givenNames; public string GivenNames { get { return givenNames; } set { if (value != givenNames) { givenNames = value; OnPropertyChanged("GivenNames"); OnPropertyChanged("FullName"); } } } string familyName; public string FamilyName { get { return familyName; } set { if (value != familyName) { familyName = value; OnPropertyChanged("FamilyName"); OnPropertyChanged("FullName"); } } } public string FullName { get { return string.Format("{0} {1}", GivenNames, FamilyName); } } public virtual void OnPropertyChanged(string propertyName) { var propertyChanged = PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }}