Must create DependencySource on same Thread as DependencyObject

走远了吗. 提交于 2019-11-30 20:04:35

The SolidColorBrush is a Freezable which is a derived DispatcherObject. DispatcherObjects have thread affinity - i.e it can only be used/interacted with on the thread on which it was created. Freezables however do offer the ability to freeze an instance. This will prevent any further changes to the object but it will also release the thread affinity. So you can either change it so that your property is not storing a DependencyObject like SolidColorBrush and instead just store the Color. Or you can freeze the SolidColorBrush that you are creating using the Freeze method.

I think the standard way is to derive the data object from Freezable and Freeze it before passing it to another thread. Once the object is frozen, you can't change it any more, so there's no danger of threading bugs.

Another option might be to make the data object a plain C# object (not derived from DispatcherObject) and implement INotifyPropertyChanged yourself.

Its not enough to set your dataGrid.ItemsSource on the main thread. You must create each item on the main-thread. Something like:

List<SomeObject> l = new List<SomeObject>();
foreach(var item in ListOfItemsInstance.ListToBind)
{
    l.Add(new SomeObject(){NameOfItem = item.NameOfItem, Properties = item.Properties });
}

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