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

怎甘沉沦 提交于 2019-12-06 08:04:46

问题


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:

Must create DependencySource on same Thread as the DependencyObject.

    // 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?


回答1:


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 View DP is created on UI thread, hence its source property i.e. GridView should also be on UI thread.

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
   }));


来源:https://stackoverflow.com/questions/12554612/must-create-dependencysource-on-same-thread-as-the-dependencyobject-when-creat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!