“必须在与DependencyObject相同的线程上创建DependencySource”时创建GridView

时间:2012-09-23 17:37:55

标签: c# wpf multithreading dispatcher

我遇到线程问题。当我想在另一个线程中将GridView设置为ListView作为View时,它会显示一条消息:

  

必须在与DependencyObject相同的线程上创建DependencySource。

    // Create grid view
                GridView grid = new GridView();
                // Add column
                // Name
                grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileName"]);
                // Type
                grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileType"]);
                // Data Modified
                grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileDataModified"]);
                // Size
                grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileSize"]);
// Edit view
            Application.Current.Dispatcher.Invoke(new Action(() => ListViewOp.View = grid));

我在做什么?

1 个答案:

答案 0 :(得分:5)

错误显示Dependency Property and its corresponding binding have to be created on same thread。它不能在不同的线程上设置。也可以在UI调度程序上创建网格。由于您的ListView View DP是在UI线程上创建的,因此它的源属性即GridView也应该在UI线程上。

Application.Current.Dispatcher.Invoke((Action)(delegate
   {
       GridView grid = new GridView();
       grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileName"]);
       grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileType"]);
       grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileDataModified"]);
       grid.Columns.Add((GridViewColumn)myresourcedictionary["gridDirFileSize"]);
       ListViewOp.View = grid
   }));