【问题标题】:Observable dictionary not behaving as expected可观察字典未按预期运行
【发布时间】:2010-05-18 14:55:42
【问题描述】:

我希望拥有“可观察”的字典,以便在其项目更改(删除或添加)时引发事件。

在其他类中,我创建了这样的字典并将绑定设置为ListBox.ItemsSourseProperty
绑定工作得很好。我可以看到这些项目。

但有些问题:事件PropertyChanged 始终为空。

谁能帮忙?

提前致谢!

class ObservableDictionary<TKey, TValue> : 
    Dictionary<TKey, TValue>, 
    INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public new void Remove(TKey obj)
    {
        base.Remove(obj);

        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs("Remove"));
        }
    }
}

【问题讨论】:

  • 在使用 new 关键字时要小心...因为该方法只会在对象被限定并强制转换为 ObservableDictionary 时调用。由于大多数框架 bindind 模型会将其转换为 IEnumerable,因此 Add & Remove 仍将调用基础 Dictionary 上的下游实现。相反,我会将您的类编写为具有内部 Dictionary 用于存储的包装类,然后实现 IDictionary 和 INotifyCollectionChanged 接口和相应的方法。
  • public class Foo { public void Bar() { Console.WriteLine("Test 1"); } } 公共类 Foo2 : Foo { public new void Bar() { Console.WriteLine("Test 2"); } } var f = new Foo2(); f.Bar(); ((Foo)f).Bar();返回测试 2 测试 1

标签: c#


【解决方案1】:

您不应为集合更改事件调用PropertyChanged。你需要实现INotifyCollectionChanged

【讨论】:

    【解决方案2】:

    您订阅了PropertyChanged 事件吗?

    var dictionary = new ObservableDictionary<int, int>();
    dictionary.PropertyChanged += 
        ( sender, args ) => MessageBox.Show( args.PropertyName );
    dictionary.Add( 1, 2 );
    dictionary.Remove( 1 );
    

    这对我有用。

    但是实现接口IDictionary 而不是使用new 关键字会更简洁。然后,您可以在您的类中使用私有 Dictionary 实例来保护您自己实现所有内容的工作。

    【讨论】:

    • 也对我有用....顺便说一句,您应该检查 base.Remove(obj) 是否确实删除了某些东西:)
    • 我将 Binding 设置为 itemsSource 的控制。 Binding 不会自动注册到 PropertyChanged 吗?
    • @yossharel,不,对于 ItemsSource,它订阅了 INotifyCollectionChanged
    【解决方案3】:

    有人订阅 Propertychanged 吗?

    对于可观察的集合,您还需要 INotifyCollectionChanged

    【讨论】:

      【解决方案4】:

      听起来您可能正在寻找ObservableCollection 的字典版本(请参阅:MSDN),它实现了INotifyCollectionChangedINotifyPropertyChanged 开箱即用。也许查看它在反射器中的实现可能会有所帮助?它可以在 System.dll 程序集的 System.Collections.ObjectModel 命名空间中找到。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-14
        • 1970-01-01
        • 2016-12-04
        • 2020-12-30
        • 2014-11-12
        • 1970-01-01
        相关资源
        最近更新 更多