从其他线程更改 Border 属性时出现异常
我在 WPF 中有一个组件,该组件使用边框,并且我使用边框背景属性来更改整个组件的背景颜色。
问题是,当我尝试使用计时器在两种不同的颜色之间交替时,会抛出 invalidOperationException 。 “调用线程无法访问该对象,因为另一个线程拥有它”。在计时器方法上,我放置了代码来更改调度程序对象中的边框属性。
mainBorder.Dispatcher.BeginInvoke((ThreadStart)delegate()
{
mainBorder.BorderBrush = myBrush;
mainBorder.Background = myBrush;
}, null);
但抛出了异常,我不明白我做错了什么!例如,同时我编写代码
lbHolderServico.Dispatcher.BeginInvoke((ThreadStart)delegate()
{
lbHolderServico.Foreground = new SolidColorBrush(HoldLabelsFontColor);
}, null);
来更改标签字体颜色,一切正常。
感谢和问候
i've a component in WPF, this component use a border and i use the border Background property to change my background color of entire component.
The problem, are when i try alternate between two different colors, with a timer, the invalidOperationException are thrown.
"The calling thread cannot access this object because a different thread owns it". On timer method i put the code to change the border properties in Dispatcher object.
mainBorder.Dispatcher.BeginInvoke((ThreadStart)delegate()
{
mainBorder.BorderBrush = myBrush;
mainBorder.Background = myBrush;
}, null);
but the exception are thrown and i not understand what i doing wrong! For example in the same time i doing it code
lbHolderServico.Dispatcher.BeginInvoke((ThreadStart)delegate()
{
lbHolderServico.Foreground = new SolidColorBrush(HoldLabelsFontColor);
}, null);
to change the label font color and everything works fine.
Thanks and regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保您也在 UI 线程上为
myBrush
创建并设置值。mainBorder
作为一个边框,具有线程关联性。但是,Brush 也具有线程关联性,如下所示它派生自 DispatcherObject。(您的第二个示例之所以有效,是因为您正在 UI 线程中创建一个新画笔,而不是使用其他地方创建的画笔...)
Make sure that you create and set values for
myBrush
on the UI thread, as well.mainBorder
, being a border, has a thread affinity. However, Brush also has thread affinity, as it is derived from DispatcherObject.(Your second example works because you're creating a new brush in the UI thread, not using one created elsewhere...)
另一种方法是将画笔/动画定义为资源,并在需要时启动动画或分配画笔。
An alternative would be to define the brushes/animations as resources and start the animations or assign the brushes when needed.