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:
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
Yup, that is correct. There are additional caveats with collections as well (The CollectionChanged
event has to be executed in the UI thread).
Usually, you are using ObservableCollection<T>
for binding to a collection. If you update this collection from a non-UI thread, the code will break, as events are fired from the same thread they are executed on (ObservableCollection<T>
fires an event when changes in the collection happen). To circumvent this, you have to supply a delegate to a custom implementation of ObservableCollection<T>
which fires the event in the UI thread (using the Dispatcher).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With