teardrop
teardrop

Reputation: 545

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

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?

Upvotes: 3

Views: 10792

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

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

Upvotes: 6

Related Questions