为什么BindingSource不告诉我哪个属性发生了变化?

时间:2013-12-06 13:00:23

标签: winforms data-binding

我正在考虑使用数据绑定 - 最简单的事情似乎是使用BindingSource来包装我的数据对象。

然而 - 当CurrentItemChanged事件告诉我属性何时发生变化时,它并没有告诉我哪一个 - 这是我需要的重要部分。

有没有办法找出哪个属性正在发生变化?

1 个答案:

答案 0 :(得分:3)

您的数据对象需要实现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);
  }
}

另见Implementing INotifyPropertyChanged - does a better way exist?