开发者

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="l开发者_运维知识库abel" 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜