[英]WPF Pass TreeView to a backgroundworker's DoWork method
I'm trying to access the header properties of a TreeView
control in a background worker's DoWork
method. 我试图在后台工作人员的
DoWork
方法中访问TreeView
控件的标头属性。
I have tried the following: 我尝试了以下方法:
var worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerAsync(MyTreeView);
private void DoWork(object sender, DoWorkEventArgs e)
{
var x = (e.Argument as TreeView);
var item1 = x.Items[0] as TreeViewItem;
//error here..
var headerItem1 = item1.Header;
}
The error that is thrown says that the property I want to access is owned by another thread (the UI thread in my case). 引发的错误表明我要访问的属性由另一个线程(在我的情况下为UI线程)拥有。
I have had this problem only with the TreeView
control so far. 到目前为止,我只有
TreeView
控件有此问题。 Passing and then accessing less 'complex' controls like Labels
or TextBlocks
has worked fine. 传递然后访问较少的“复杂”控件(如
Labels
或TextBlocks
)效果很好。
Thanks for every answer. 谢谢你的回答。
The rule is: only access the GUI elements (controls) on the GUI thread . 规则是: 仅访问GUI线程上的GUI元素(控件) 。
In a BackgroundWorker
, the DoWork
event handler will be called on a background thread. 在
BackgroundWorker
,将在后台线程上调用DoWork
事件处理程序。 You are not allowed to access the GUI elements on that thread. 不允许您访问该线程上的GUI元素。 Accessing means reading or writing properties (or indexers) or calling methods.
访问是指读取或写入属性(或索引器)或调用方法。
If you need to do something with a control on a background thread, use Dispatcher.Invoke
method. 如果您需要对后台线程上的控件执行某些操作,请使用
Dispatcher.Invoke
方法。 But be warned, that using the Invoke
/ BeginInvoke
methods might impact the overall performance (eg when used in a tight loop). 但请注意,使用
Invoke
/ BeginInvoke
方法可能会影响整体性能(例如,在紧密循环中使用时)。
You have to redesign your logic in such a manner that you don't need to access the GUI elements on a background thread. 您必须以不需要访问后台线程上的GUI元素的方式重新设计逻辑。 This would be the best solution.
这将是最好的解决方案。
By the way, I would recommend you to move from the BackgroundWorker
to the modern asynchronous patterns ( async
/ await
& Task
s). 顺便说一句,我建议您从
BackgroundWorker
转到现代异步模式( async
/ await
& Task
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.