相关疑难解决方法(0)

升级到.NET 4.5:ItemsControl与其项目源不一致

我正在构建一个应用程序,它使用许多ItemControls(datagrids和listviews).为了从后台线程轻松更新这些列表,我将此扩展用于ObservableCollections,它运行良好:

http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx

今天我安装了VS12(后来安装了.NET 4.5),因为我想使用为.NET 4.5编写的组件.在将我的项目升级到.NET 4.5(从4.0)之前,我的数据网格从workerthread更新时开始抛出InvalidOperationException.异常消息:

抛出此异常是因为控件'System.Windows.Controls.DataGrid Items.Count:5'的名称为'(未命名)'的生成器已收到与Items集合的当前状态不一致的CollectionChanged事件序列.检测到以下差异:累计计数4与实际计数5不同.[累计计数为(上次重置时计数+ #Adds - 自上次重置后自上次复位).

Repro代码:

XAML:

<Window x:Class="Test1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
   <Grid>
      <DataGrid ItemsSource="{Binding Items, Mode=OneTime}" PresentationTraceSources.TraceLevel="High"/>       
   </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

码:

public partial class MainWindow : Window
{
    public ExtendedObservableCollection<int> Items { get; private set; }

    public MainWindow()
    {
        InitializeComponent();
        Items = new ExtendedObservableCollection<int>();
        DataContext = this;
        Loaded += MainWindow_Loaded;
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
            Task.Factory.StartNew(() =>
            {
                foreach (var item in Enumerable.Range(1, 500))
                {
                    Items.Add(item);
                }
            });                
    }
}
Run Code Online (Sandbox Code Playgroud)

c# wpfdatagrid .net-4.5

26
推荐指数
3
解决办法
2万
查看次数

标签 统计

.net-4.5 ×1

c# ×1

wpfdatagrid ×1