前文中
【WPF绑定2】 INotifyPropertyChanged Or 依赖属性_code bean的博客-CSDN博客_wpf 通知属性
介绍了 INotifyPropertyChanged的使用
- // 建议数据模型如果要做数据变化通知 ,使用INotifyPropertyChanged
- // 使用时是需要实例化的
- // DataClass dataClass=new DataClass();
- public class DataClass : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
-
- private int _value;
-
- public int Value
- {
- get { return _value; }
- set
- {
- _value = value;
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
- }
- }
-
- }
如果属性不多还好,如果属性多了,岂不是要写一堆的代码?此时Fody就登场了。
NuGet 中搜寻Fody,找到如下包,进行安装

首先再类上添加特性[AddINotifyPropertyChangedInterface]
那么该类下的所有的属性,都会被自动加上属性通知,如果你有特殊的要求,再在特定的属性上加上特殊的特性。
具体如下代码所示:
- [AddINotifyPropertyChangedInterface]
- public class Data
- {
- /*
- AlsoNotifyFoA 实现通知的时候,同时通知其属性
- DoNotNotify 指定不需要通知相关的代码
- DependsOn 指定哪些属性变化的时候,通知当前属性变化
- DoNotCheckEquality 强制不做旧值比对(默认情况会自动添加比对代码)
- */
-
- ///
- /// 不加的情况下,做旧值比对后通知
- ///
- public int LinkCount { get; set; } = 0;
- public int ErrCount { get; set; } = 0;
- public int Count { get; set; } = 0;
-
-
- #region 举例说明
- ///
- /// DoNotNotify 指定不需要通知相关的代码
- ///
- [DoNotNotify]
- public int Test { get; set; }
-
-
- ///
- /// DependsOn 指定哪些属性变化的时候,通知当前属性变化
- /// 及当属性Test发生变化时,Test1触发属性通知
- ///
- [DependsOn("Test")]
- public int Test1 { get; set; }
-
- ///
- /// 实现通知的时候,同时通知其属性
- /// Test2实现通知的时候,同时通知Test
- ///
- [AlsoNotifyFor("Test")]
- public int Test2 { get; set; }
-
- ///
- /// DoNotCheckEquality 强制不做旧值比对(默认情况会自动添加比对代码,即数值没有发生改变时不通知)
- /// 加上后只要有个属性访问就会通知,不管值是否变化
- ///
- [DoNotCheckEquality]
- public int Test3 { get; set; }
- #endregion
-
- }
之后加入MVVM框架之后,应该可以替代掉Fody。