目前,我正在编写自己的字典,它实现了INotifyPropertyChanged。请参见下面:
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
new public Item this[TKey key]
{
get { return base.Item[key]; }
set(TValue value)
{
if (base.Item[key] != value)
{
base.Item[key] = value;
OnPropertyChanged("XXX"); // what string should I use?
}
}
}
我的目标很简单:当字典中某个值发生更改时,通知该值已更改。所有与相应键名绑定的 WPF 元素都应更新自己。
现在我的问题是:我应该使用什么字符串作为propertyName
来通知?
我尝试过"[" + key.ToString() + "]"
、"Item[" + key.ToString() + "]"
以及简单的key.ToString()
,但它们似乎都不起作用,因为 WPF 元素没有更新。
使用 String.Empty
(""
)会更新 WPF 元素,但我不使用它,因为这将更新所有绑定同一字典的 WPF 元素,即使它们具有不同的键。
这是我在 XAML 中的绑定:
<TextBlock DataContext="{Binding Dictionary}" Text="{Binding [Index]}" />
Index
当然是我的字典中键的名称。
有些人建议不要使用 INotifyPropertyChanged,而是使用 INotifyCollectionChanged。我尝试了这样做:
Dim index As Integer = MyBase.Keys.ToList().IndexOf(key)
Dim changedItem As Object = MyBase.ToList().ElementAt(index)
RaiseEvent CollectionChanged(Me, New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, changedItem, index))
但这并不会更新绑定的 WPF 元素。