最简单的方式来实现属性更改的自动通知 [英] Simplest way to achieve automatic notification of property change

查看:113
本文介绍了最简单的方式来实现属性更改的自动通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有解决方案在那里执行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):

  • Aspect Examples (INotifyPropertyChanged via aspects)
  • LinFu
  • INotifyPropertyChanged auto wiring or how to get rid of redundant code
  • 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.

您code

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆