WPF线程:我可以更新非UI线程中的控件的数据上下文吗? [英] WPF threading: can I update a control's data context in a non-UI thread?
问题描述
我们可以更新WPF控件在一个非UI线程的数据上下文?
Can we update the data context of a WPF control in a non-UI thread?
假设我们有一个标签
有 MyClass的
作为数据上下文,并绑定内容
到 myProperty的
:
Say we have a Label
that has MyClass
as data context, and bind Content
to MyProperty
:
<标签名称=标签CONTENT ={结合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 =更新
来更新标签的内容,但我们不能 label.Content =更新
直接做。那是正确的。
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?
我自己的答案:
下面就是我发现:
- 从一个非UI线程,您不能更新控制;
- 从一个非UI线程,您可以控件的数据上下文的更新属性;
- 从一个非UI线程,您不能添加项目或删除从项目
ObserverableCollection
绑定到一个控制。但是有一个解决方法: http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to- a.aspx
- 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
推荐答案
是啊,这是正确的。没有与集合,以及(在 CollectionChanged
事件具有在UI线程中执行)的其他注意事项。
Yup, that is correct. There are additional caveats with collections as well (The CollectionChanged
event has to be executed in the UI thread).
通常情况下,你使用的ObservableCollection< T>
用于绑定到集合。如果从非UI线程更新此集合,代码将打破,因为事件是由他们的意见(执行相同的线程中触发的ObservableCollection< T>
触发一个事件当集合中的改变发生)。为了克服这一点,你必须委托供给的自定义实现的ObservableCollection< T>
这触发在UI线程事件(使用分派器)
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).
这篇关于WPF线程:我可以更新非UI线程中的控件的数据上下文吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!