【问题标题】:Where / When / How does BindingList<T> convert / wireup PropertyChanged to ListChanged eventBindingList<T> 在哪里/何时/如何将 PropertyChanged 转换为 ListChanged 事件
【发布时间】:2010-11-12 10:09:25
【问题描述】:

我有一个全部实现 INotifyPropertyChanged 的​​对象层次结构。我还有一个从 BindingList 派生的自定义列表。

我的理解是,当我将一个包含 INotifyPropertyChanged 元素的对象添加到列表时,PropertyChanged 事件会以某种方式自动连接/转换为 ListChanged 事件。

但是,在我将列表设置为 DataGridView 的数据源后,当我更改网格中的值时,ListChanged 事件不会触发...当我进入代码时,事实证明 PropertyChanged()事件没有触发,因为它是空的,我认为这意味着它没有被连接/转换为 BindingList 的 ListChanged 事件,就像它应该做的那样......

例如:

public class Foo : INotifyPropertyChanged
{
     //Properties...
     private string _bar = string.Empty;
     public string Bar
     {
         get { return this._bar; }
         set
         {
              if (this._bar != value)
              {
                  this._bar = value;
                  this.NotifyPropertyChanged("Bar");
              }
         }
     }

     //Constructor(s)...
     public Foo(object seed)
     {
         this._bar = (string)object;
     }

     //PropertyChanged event handling...
     public event PropertyChangedEventHandler PropertyChanged;
     protected void NotifyPropertyChanged(String info)
     {
         if (this.PropertyChanged != null)
         {
             this.PropertyChanged(this, new PropertyChangedEventArgs(info));
         }
     }
}

这是我的自定义列表类...

public class FooBarList : BindingList<Foo>
{
     public FooBarList(object[] seed)
     {
          for (int i = 0; i < seed.Length; i++)
          {
             this.Items.Add(new Foo(this._seed[i]));
          }
     }
}

有什么想法或建议吗?

谢谢!

乔什

【问题讨论】:

    标签: datagridview datasource inotifypropertychanged bindinglist


    【解决方案1】:

    我认为问题在于您调用的是this.Items.Add() 而不是this.Add()Items 属性返回基类List&lt;T&gt;,其Add() 方法没有您想要的功能。

    【讨论】:

    • 谢谢 Ben... 这似乎成功了... 另一方面,您是否知道 BindingList 使用对象的 Equals() 方法来确定哪个列表项已更改?我问是因为我的自定义对象都具有 IEquatable 的自定义实现,并且看起来每当触发 PropertyChanged 事件时,都会调用每个对象的 Equals() 方法,直到其中一个返回 true...
    • BindingList 的 PropertyChanged 处理程序使用 List.IndexOf(),它(间接)调用您的 IEquatable.Equals() 实现。没有办法阻止这种行为,所以如果您担心性能但绝对必须使用 BindingList,您可以考虑将比较逻辑提取到实现 IComparer 的单独类中——如果这在您的应用中完全可行的话场景。
    • 好的...我专门重写 IEquatable 实现并不重要,所以我在我的通用基础中创建了一个抽象方法:public abstract bool EqualTo(T obj);这解决了我的问题...再次感谢!
    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 2012-10-28
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多