Question

You cannot bind to a WPF DataGrid's Columns property, so a workaround is to use use an attached property as found in this SO question/answer. My viewmodel exposes an ObservableCollection containing the DataGridColumns, and I bind it to the DataGrid via this attached property.

A background thread is responsible for populating the collection, and I'm using Dispatcher.Invoke to do this, which I thought would avoid threading issues. The background thread itself works fine, but an exception is raised in the above attached property code:

The calling thread cannot access this object because a different thread owns it.

(in the else if that deals with an Add action, specifically the line dataGrid.Columns.Add(column);).

Any idea what might be wrong?

Was it helpful?

Solution

If you are using .NET 4.5, the simplest option is to use BindingOperations.EnableCollectionSynchronization. This allows you to update a collection on a background thread directly, without worrying about synchronization in the binding.

Otherwise, you need to make sure that all changes to your collection happen on the user interface thread. Using Dispatcher.Invoke should work (provided you get the correct Dispatcher instance), though there are more elegant solutions, such as the binding collections in The Helper Trinity and other projects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top