如何避免手动实现INotifyPropertyChanged

Max*_*Max 8 c# data-binding collections winforms

有没有办法避免这种情况.我有很多绑定到DataGridViews的类,它们只是带有默认getter和setter的简单属性集合.所以这些类非常简单.现在我需要为它们实现INotifyPropertyChanged接口,这将增加很多代码量.是否有任何类可以继承以避免编写所有这些无聊的代码?我认为我可以从某个类继承我的类,并用一些属性装饰属性,它会发挥魔力.那可能吗?

我很清楚面向方面编程,但我更倾向于以面向对象的方式.

Mar*_*ell 9

这取决于; 你可以使用PostSharp来编写一个由编织者重写的属性; 但是,我很想手动完成它 - 也许使用一种常用的方法来处理数据更新,即

private string name;
public string Name {
    get { return name; }
    set { Notify.SetField(ref name, value, PropertyChanged, this, "Name"); }
}
Run Code Online (Sandbox Code Playgroud)

有:

public static class Notify {
    public static bool SetField<T>(ref T field, T value,
         PropertyChangedEventHandler handler, object sender, string propertyName)
    {
        if(!EqualityComparer<T>.Default.Equals(field,value)) {
            field = value;
            if(handler!=null) {
                handler(sender, new PropertyChangedEventArgs(propertyName));
            }
            return true;
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)


lep*_*pie 5

创建一个容器基类,例如:

abstract class Container : INotifyPropertyChanged
{
  Dictionary<string, object> values;

  protected object this[string name]
  {
    get {return values[name]; }
    set 
    { 
      values[name] = value;
      PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
  }
}

class Foo : Container
{
  public int Bar 
  {
    {get {return (int) this["Bar"]; }}
    {set { this["Bar"] = value; } }
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:非常简化的代码