当您实现INotifyPropertyChanged接口时,您负责在类中更新属性时调用PropertyChanged事件.
这通常导致以下代码:
public class MyClass: INotifyPropertyChanged private bool myfield; public bool MyField { get { return myfield; } set { if (myfield == value) return; myfield = value; OnPropertyChanged(new PropertyChangedEventArgs("MyField")); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler h = PropertyChanged; if (h != null) h(this,e); } }
这是每个财产12行.
[INotifyProperty] public double MyField{ get; set; }
但不幸的是这是不可能的(例如,见msdn上的this post)
如何减少每个物业所需的代码量?
解决方法
其实,每件物业只有3-4线;其他行通过所有“通知”属性摊销:
class Person : INotifyPropertyChanged { #region INotifyPropertyChanged: Shared bit public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this,e); } #endregion private string _firstName; public string FirstName { get { return _firstName; } set { if (_firstName == value) return; _firstName = value; OnPropertyChanged(new PropertyChangedEventArgs("FirstName")); } } // Ditto for other properties }
private string _firstName; public string FirstName { get { return _firstName; } set { SetNotifyingProperty("FirstName",ref _firstName,value); } } private void SetNotifyingProperty<T>(string propertyName,ref T field,T value) { if (value.Equals(field)) return; field = value; OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); }