How to avoid implementing INotifyPropertyChanged manually

后端 未结 7 1746
名媛妹妹
名媛妹妹 2021-01-05 02:44

Is there some way to avoid this. I have a lot of classes that are bound to DataGridViews and they are just simple collection of properties with default getter and setter. So

7条回答
  •  猫巷女王i
    2021-01-05 03:18

    It depends; you could use PostSharp to write such an attribute that is re-written by the weaver; however, I would be tempted to just do it manually - perhaps using a common method for handling the data updates, i.e.

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

    with:

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

提交回复
热议问题