用于 c# 的 ObservableDictionary
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10616554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ObservableDictionary for c#
提问by Arsen Zahray
I'm trying to use following implementation of the ObservableDictionary: ObservableDictionary (C#).
我正在尝试使用 ObservableDictionary: ObservableDictionary (C#) 的以下实现。
When I'm using following code while binding the dictionary to a DataGrid:
当我在将字典绑定到 DataGrid 时使用以下代码时:
ObserveableDictionary<string,string> dd=new ObserveableDictionary<string,string>();
....
dd["aa"]="bb";
....
dd["aa"]="cc";
at dd["aa"]="cc";I'm getting following exception
在dd["aa"]="cc";我收到以下异常
Index was out of range. Must be non-negative and less than the size of the
collection. Parameter name: index
This exception is thrown in CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem)in the following method:
CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem)在以下方法中抛出此异常:
private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> newItem, KeyValuePair<TKey, TValue> oldItem)
{
OnPropertyChanged();
if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem));
}
The indexparam seems to correspond to KeyValuePair<TKey, TValue> oldItem.
该indexPARAM似乎对应KeyValuePair<TKey, TValue> oldItem。
How can KeyValuePair<TKey, TValue>be out of range, and what should I do to make this work?
怎么KeyValuePair<TKey, TValue>会超出范围,我应该怎么做才能使这项工作?
采纳答案by Tilak
Similar data structure, to bind to Dictionary type collection
类似的数据结构,绑定到 Dictionary 类型集合
http://drwpf.com/blog/2007/09/16/can-i-bind-my-itemscontrol-to-a-dictionary/
http://drwpf.com/blog/2007/09/16/can-i-bind-my-itemscontrol-to-a-dictionary/
It provides a new Data structure ObservableDictionary and fires PropertyChangedin case of any change to underlying Dictionary.
它提供了一个新的数据结构 ObservableDictionary 并在底层 Dictionary 发生任何更改时触发PropertyChanged。
回答by Arsen Zahray
here's what I did in the end:
这是我最后所做的:
[Serializable]
public class ObservableKeyValuePair<TKey,TValue>:INotifyPropertyChanged
{
#region properties
private TKey key;
private TValue value;
public TKey Key
{
get { return key; }
set
{
key = value;
OnPropertyChanged("Key");
}
}
public TValue Value
{
get { return value; }
set
{
this.value = value;
OnPropertyChanged("Value");
}
}
#endregion
#region INotifyPropertyChanged Members
[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(name));
}
#endregion
}
[Serializable]
public class ObservableDictionary<TKey,TValue>:ObservableCollection<ObservableKeyValuePair<TKey,TValue>>, IDictionary<TKey,TValue>
{
#region IDictionary<TKey,TValue> Members
public void Add(TKey key, TValue value)
{
if (ContainsKey(key))
{
throw new ArgumentException("The dictionary already contains the key");
}
base.Add(new ObservableKeyValuePair<TKey, TValue>() {Key = key, Value = value});
}
public bool ContainsKey(TKey key)
{
//var m=base.FirstOrDefault((i) => i.Key == key);
var r = ThisAsCollection().FirstOrDefault((i) => Equals(key, i.Key));
return !Equals(default(ObservableKeyValuePair<TKey, TValue>), r);
}
bool Equals<TKey>(TKey a, TKey b)
{
return EqualityComparer<TKey>.Default.Equals(a, b);
}
private ObservableCollection<ObservableKeyValuePair<TKey, TValue>> ThisAsCollection()
{
return this;
}
public ICollection<TKey> Keys
{
get { return (from i in ThisAsCollection() select i.Key).ToList(); }
}
public bool Remove(TKey key)
{
var remove = ThisAsCollection().Where(pair => Equals(key, pair.Key)).ToList();
foreach (var pair in remove)
{
ThisAsCollection().Remove(pair);
}
return remove.Count > 0;
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
var r = GetKvpByTheKey(key);
if (!Equals(r, default(ObservableKeyValuePair<TKey, TValue>)))
{
return false;
}
value = r.Value;
return true;
}
private ObservableKeyValuePair<TKey, TValue> GetKvpByTheKey(TKey key)
{
return ThisAsCollection().FirstOrDefault((i) => i.Key.Equals(key));
}
public ICollection<TValue> Values
{
get { return (from i in ThisAsCollection() select i.Value).ToList(); }
}
public TValue this[TKey key]
{
get
{
TValue result;
if (!TryGetValue(key,out result))
{
throw new ArgumentException("Key not found");
}
return result;
}
set
{
if (ContainsKey(key))
{
GetKvpByTheKey(key).Value = value;
}
else
{
Add(key, value);
}
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
var r = GetKvpByTheKey(item.Key);
if (Equals(r, default(ObservableKeyValuePair<TKey, TValue>)))
{
return false;
}
return Equals(r.Value, item.Value);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
var r = GetKvpByTheKey(item.Key);
if (Equals(r, default(ObservableKeyValuePair<TKey, TValue>)))
{
return false;
}
if (!Equals(r.Value,item.Value))
{
return false ;
}
return ThisAsCollection().Remove(r);
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
public new IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return (from i in ThisAsCollection() select new KeyValuePair<TKey, TValue>(i.Key, i.Value)).ToList().GetEnumerator();
}
#endregion
}
This implementation looks and feels like dictionary to the user and like ObservableCollection to WPF
这个实现对于用户来说就像字典一样,对于 WPF 来说就像 ObservableCollection
回答by Rakshith Balasubramanya
Even I am using the ObservableDictionary of github, I also faced this exception. I had declared the dictionary variable at class level later I tried to create a new instance in the method where it was getting accessed.
即使我使用 github 的 ObservableDictionary,我也遇到了这个异常。我在类级别声明了字典变量后来我尝试在它被访问的方法中创建一个新实例。
OldCode which gave exception:
OldCode 给出了异常:
public class CName
{
ObservableDictionary<string, string> _classVariableDictionary = new ObservableDictionary<string, string>();
}
NewCode which worked:
新代码有效:
public void MethodName()
{
ObservableDictionary<string, string> _localVariableDictionary = new ObservableDictionary<string, string>();
}
回答by The Lonely Coder
ObservableDictionary was added to the .Net Framework at version 4.5:-
ObservableDictionary 已添加到 .Net Framework 4.5 版:-
https://zamjad.wordpress.com/2012/10/12/observabledictionary-in-net-4-5/
https://zamjad.wordpress.com/2012/10/12/observabledictionary-in-net-4-5/
Here is a link to the latest source code:-
这是最新源代码的链接:-
回答by ztorstri
I ended up writing a class to hold the Key-Value pair and using a collection of that class. I'm using Caliburn Micro which is where the BindableCollection comes from, but an ObservableCollection should work the same way. I use the MVVM pattern.
我最终编写了一个类来保存键值对并使用该类的集合。我正在使用 Caliburn Micro,它是 BindableCollection 的来源,但 ObservableCollection 应该以相同的方式工作。我使用 MVVM 模式。
the viewmodel
视图模型
using Caliburn.Micro;
private BindableCollection<KeyValuePair> _items;
public BindableCollection<KeyValuePair> Items
{
get { return _items; }
set
{
if (_items != value)
{
_items = value;
NotifyOfPropertyChange(() => Items);
}
}
}
the custom keyValuePair
自定义键值对
public class KeyValuePair
{
public string Key { get; set; }
public string Value { get; set; }
}
and in the view
并且在视图中
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0"
Text="{Binding Key, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Column="1"
Text="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
It bothers me that I can't just bind to a dictionary, but I find this much easier and cleaner than writing an ObservableDictionary from scratch and worrying about the change notifications.
让我烦恼的是我不能只绑定到字典,但我发现这比从头开始编写 ObservableDictionary 并担心更改通知更容易和更清晰。

