实现属性更改自动通知的最简单方法 [英] Simplest way to achieve automatic notification of property change
问题描述
我知道有实现 INotifyPropertyChanged 的解决方案,但没有一个像:引用这个库,创建/添加这个属性,完成(我在这里考虑面向方面编程).有谁知道一个非常简单的方法来做到这一点?如果解决方案是免费的,则加分.
I know that there are solutions out there for implementing INotifyPropertyChanged, but none of them are as simple as: reference this library, create/add this attribute, done (I'm thinking Aspect-Oriented Programming here). Does anyone know of a really simple way to do this? Bonus points if the solution is free.
以下是一些相关链接(没有一个提供足够简单的答案):
Here are some relevant links (none of which provide a simple enough answer):
- 方面示例(INotifyPropertyChanged 通过方面)
- LinFu
- INotifyPropertyChanged 自动接线或如何去除多余的代码
- INotifyPropertyChanged with Unity Interception AOP
推荐答案
试试这个https://github.com/Fody/PropertyChanged
它将编织实现 INotifyPropertyChanged 甚至处理依赖项的类型的所有属性.
It will weave all properties of types that implement INotifyPropertyChanged and even handles dependencies.
您的代码
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string GivenNames { get; set; }
public string FamilyName { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
}
编译什么
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string givenNames;
public string GivenNames
{
get { return givenNames; }
set
{
if (value != givenNames)
{
givenNames = value;
OnPropertyChanged("GivenNames");
OnPropertyChanged("FullName");
}
}
}
private 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 void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
或者您可以使用属性进行更细粒度的控制.
Or you can use attributes for more fine grained control.
这篇关于实现属性更改自动通知的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!