Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF threading: can I update a control's data context in a non-UI thread?

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
like image 806
Shuo Avatar asked Dec 11 '10 20:12

Shuo


1 Answers

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).

like image 173
Femaref Avatar answered Nov 10 '22 18:11

Femaref