Winforms 为什么BindingSource不告诉我哪个属性已更改?

Winforms 为什么BindingSource不告诉我哪个属性已更改?,winforms,data-binding,Winforms,Data Binding,我正在考虑使用数据绑定——最简单的方法似乎是使用BindingSource来包装数据对象 然而,虽然CurrentItemChanged事件告诉我某个属性何时发生了更改,但它不会告诉我是哪一个,这是我所需要的一个重要部分 有没有办法找出哪个属性正在更改?您的数据对象需要实现INotifyPropertyChanged接口: public class MyObject : INotifyPropertyChanged { public event PropertyChangedEventHan

我正在考虑使用数据绑定——最简单的方法似乎是使用BindingSource来包装数据对象

然而,虽然CurrentItemChanged事件告诉我某个属性何时发生了更改,但它不会告诉我是哪一个,这是我所需要的一个重要部分


有没有办法找出哪个属性正在更改?

您的数据对象需要实现INotifyPropertyChanged接口:

public class MyObject : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;
  private string textData = string.Empty;

  protected void OnPropertyChanged(string propertyName) {
    if (PropertyChanged != null) {
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
  }

  public string TextData {
    get { return textData; }
    set {
      if (value != textData) {
        textData = value;
        OnPropertyChanged("TextData");
      }
    }
  }
}
然后,如果使用BindingList,则可以使用BindingSource的ListChanged事件查看更改的属性:

BindingList<MyObject> items = new BindingList<MyObject>();
BindingSource bs = new BindingSource();

protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);
  items.Add(new MyObject() { TextData  = "default text" });
  bs.DataSource = items;
  bs.ListChanged += bs_ListChanged;
  items[0].TextData = "Changed Text";
}

void bs_ListChanged(object sender, ListChangedEventArgs e) {
  if (e.PropertyDescriptor != null) {
    MessageBox.Show(e.PropertyDescriptor.Name);
  }
}
BindingList项=新建BindingList();
BindingSource bs=新的BindingSource();
受保护的覆盖无效加载(事件参数e){
基础荷载(e);
添加(新的MyObject(){TextData=“default text”});
bs.DataSource=项目;
bs.ListChanged+=bs_ListChanged;
项[0]。TextData=“已更改的文本”;
}
无效bs_ListChanged(对象发送方,ListChangedEventArgs e){
如果(例如,PropertyDescriptor!=null){
MessageBox.Show(e.PropertyDescriptor.Name);
}
}

另请参见

谢谢。很遗憾BindingList不能自动完成这项工作,您可能会认为它会更聪明。。。