DataBinding/WPF C# 的通用可观察字典类 [英] General Observable Dictionary Class for DataBinding/WPF C#
问题描述
我正在尝试在 C# 中为 WPF 数据绑定创建一个 Observable 字典类.我在这里找到了 Andy 的一个很好的例子:双向数据在 WPF 中绑定字典
I'm trying to create a Observable Dictionary Class for WPF DataBinding in C#. I found a nice example from Andy here: Two Way Data Binding With a Dictionary in WPF
据此,我尝试将代码更改为以下内容:
According to that, I tried to change the code to following:
class ObservableDictionary : ViewModelBase
{
public ObservableDictionary(Dictionary<TKey, TValue> dictionary)
{
_data = dictionary;
}
private Dictionary<TKey, TValue> _data;
public Dictionary<TKey, TValue> Data
{
get { return this._data; }
}
private KeyValuePair<TKey, TValue>? _selectedKey = null;
public KeyValuePair<TKey, TValue>? SelectedKey
{
get { return _selectedKey; }
set
{
_selectedKey = value;
RaisePropertyChanged("SelectedKey");
RaisePropertyChanged("SelectedValue");
}
}
public TValue SelectedValue
{
get
{
return _data[SelectedKey.Value.Key];
}
set
{
_data[SelectedKey.Value.Key] = value;
RaisePropertyChanged("SelectedValue");
}
}
}
}
不幸的是,我仍然不知道如何传递通用"字典对象..有什么想法吗?
Unfortunately I still don't know how to pass "general" Dictionary Objects.. any ideas?
谢谢!
干杯
推荐答案
如果你真的想制作一个 ObservableDictionary
,我建议你创建一个同时实现 IDictionary
的类> 和 INotifyCollectionChanged
.您始终可以在内部使用 Dictionary
来实现 IDictionary
的方法,这样您就不必自己重新实现.
If you really want to make an ObservableDictionary
, I'd suggest creating a class that implements both IDictionary
and INotifyCollectionChanged
. You can always use a Dictionary
internally to implement the methods of IDictionary
so that you won't have to reimplement that yourself.
由于您完全了解内部 Dictionary
何时发生变化,您可以使用这些知识来实现 INotifyCollectionChanged
.
Since you have full knowledge of when the internal Dictionary
changes, you can use that knowledge to implement INotifyCollectionChanged
.
这篇关于DataBinding/WPF C# 的通用可观察字典类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!