【发布时间】:2012-08-05 18:07:30
【问题描述】:
我遇到了一个奇怪的情况,我实现了一个 ObservableConcurrentDictionary(基于 .NET 的 ConcurrentDictionary),我曾经用它来实现 ObservableConcurrentCollection(它只是自动设置 Dictionary 中的 Key 属性,并具有所有 IList、IEnumerable、IQueryable 和 ICollection 方法)。当我执行以下操作时,一切正常:
ObservableConcurrentCollection<string> items = new ObservableConcurrentCollection<string>();
dataGrid.ItemsSource = items;
items.Add("TEST");
这在 DataGrid 中得到了完美体现。
但是,当我这样做时:
ObservableConcurrentCollection<string> items = new ObservableConcurrentCollection<string>();
items.Add("TEST"); // <-- Notice that this and the line below are swapped.
dataGrid.ItemsSource = items;
它无法正常工作,因为“项目”中的项目突然变成了 KeyValuePair。我可以通过在最后一行中使用 dataGrid.ItemsSource = items.Values 轻松解决此问题,但我宁愿让它像上一个一样工作(而且它也令人困惑)。
【问题讨论】:
-
如果没有看到 ObservableConcurrentCollection 的实现,真的很难对此发表评论。但问题可能出在您的Indexer
-
代码并没有什么特别之处,ObservableConcurrentDictionary 只是 ConcurrentDictionary 的包装器,带有 OnCollectionChanged 事件。 ObservableConcurrentCollection 使用标准的 IList 内容(自动获取和设置 ObservableConcurrentDictionary 的键)加上 IEnumerable 和 Indexer 更改为值。但是 ObservableConcurrentCollection 的索引器甚至没有被调用。
标签: c# wpf data-binding binding itemssource