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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12554612/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:30:01  来源:igfitidea点击:

"Must create DependencySource on same Thread as the DependencyObject" When Create GridView

c#wpfmultithreadingdispatcher

提问by teardrop

I have a problem with thread.When I want set a GridView into a ListView as View in another thread.It display a message which said:

我的线程有问题。当我想将 GridView 设置为 ListView 作为另一个线程中的视图时。它显示一条消息:

Must create DependencySource on same Thread as the DependencyObject.

必须在与 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));

What am I doing?

我在做什么?

回答by Rohit Vats

As the error says Dependency Property and its corresponding binding have to be created on same thread. It can't be set on different threads. Put the creation of grid on UI dispatcher too. Since your ListView ViewDP is created on UI thread, hence its source property i.e. GridViewshould also be on UI thread.

正如错误所说Dependency Property and its corresponding binding have to be created on same thread。不能在不同的线程上设置。将网格的创建也放在 UI 调度程序上。由于您的 ListView ViewDP 是在 UI 线程上创建的,因此它的源属性 ieGridView也应该在 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
   }));