Can we update the data context of a WPF control in a non-UI thread?
Say we have a Label
that has MyClass
as data context, and bind Content
to MyProperty
:
<Label Name="label" Content="{Binding MyProperty}" />
,
where MyClass
is simply:
public class MyClass : INotifyPropertyChanged
{
int _myField;
public int MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
PropertyChanged(this, new PropertyChangedEventArgs("MyProperty"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
In a non-UI thread, we can do myClass.MyProperty = "updated"
to update the content of the label, but we cannot do label.Content = "updated"
directly. Is that correct?
My own answer:
Here's what I've found:
- From a non-UI thread, you cannot update a control;
- From a non-UI thread, you can update properties of a control's data context;
- From a non-UI thread, you cannot add items to or remove items from an
ObserverableCollection
that is bound to a control. But there is a workaround: http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx