【发布时间】:2010-12-11 20:25:04
【问题描述】:
我们可以在非 UI 线程中更新 WPF 控件的数据上下文吗?
假设我们有一个Label 以MyClass 作为数据上下文,并将Content 绑定到MyProperty:
<Label Name="label" Content="{Binding MyProperty}" />,
MyClass 就是:
public class MyClass : INotifyPropertyChanged
{
int _myField;
public int MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
PropertyChanged(this, new PropertyChangedEventArgs("MyProperty"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
在非UI线程中,我们可以做myClass.MyProperty = "updated"来更新标签的内容,但是我们不能直接做label.Content = "updated"。对吗?
我自己的回答:
这是我发现的:
- 从非 UI 线程,您无法更新控件;
- 从非 UI 线程,您可以更新控件数据上下文的属性;
- 在非 UI 线程中,您不能向绑定到控件的
ObserverableCollection添加项目或从中删除项目。但是有一个解决方法:http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx
【问题讨论】:
标签: c# wpf multithreading