【问题标题】:Why does BindingSource not tell me which property has changed?为什么 BindingSource 不告诉我哪个属性发生了变化?
【发布时间】:2013-12-23 20:13:53
【问题描述】:

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

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

有什么方法可以查出哪个属性发生了变化?

【问题讨论】:

    标签: winforms data-binding


    【解决方案1】:

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

    【讨论】:

    • 谢谢。遗憾的是 BindingList 不能自动执行此操作,您会认为它会更智能...
    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 2021-04-10
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2020-04-10
    相关资源
    最近更新 更多