0

我有一个奇怪的情况,我已经实现了一个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 轻松解决此问题,但我宁愿让它像前一个一样工作(而且它也令人困惑)。

4

3 回答 3

0

由于您的新 ObservableConcurrentDictionary 类基于 ConcurrentDictionary,我怀疑问题出在接口方法之一的实现中。

没有看到该类,很难诊断,但我怀疑问题出在返回整个字典条目而不是键指定的值的检索实现之一中。

例如,当 ItemsSource 在第二种情况下绑定到网格时,它可能会通过 IEnumerable 检索值,而当您在第一种情况下调用 Add 时,它会触发包含正确信息的 observable 事件。

通过在可疑检索方法中放置断点或在分配 ItemsSource 时进入第二种情况的代码,应该相当简单地找出问题发生在哪里。这应该会很快向您显示正在执行的方法,并显示正在返回字典条目而不是值。

于 2012-08-05T18:23:38.813 回答
0

对我来说,我总是用这个

<DataGrid ItemsSource="{Binding}" x:Name="datagrid" >

然后

ObservableConcurrentCollection<string> items = new ObservableConcurrentCollection<string>();
items.Add("TEST"); 
dataGrid.DataContext = items;

你可以试试这个,即使我换了台词,它也对我有用

于 2012-08-06T05:04:25.357 回答
0

通过更改 ObservableConcurrentCollection 解决了这个问题,我删除了继承并为 ObservableConcurrentDictionary 创建了一个字段。现在就像一个魅力。

于 2012-08-06T11:45:03.297 回答