Why does BindingSource not tell me which property has changed?

别等时光非礼了梦想. 提交于 2021-02-07 19:30:07

问题


I'm looking at using databinding - and the simplest thing to do seems to be to use a BindingSource to wrap my data objects.

However - while the CurrentItemChanged event tells me when a property has changed, it doesn't tell me which one - and that's a vital part of what I need.

Is there any way to find out which property is changing?


回答1:


Your data objects need to implement the INotifyPropertyChanged interface:

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");
      }
    }
  }
}

Then if you use BindingList, you can use the BindingSource's ListChanged event to see which property changed:

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);
  }
}

Also see Implementing INotifyPropertyChanged - does a better way exist?



来源:https://stackoverflow.com/questions/20424554/why-does-bindingsource-not-tell-me-which-property-has-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!