如何使用抛出 InvalidOperationException 的计时器更改标签内容
我正在制作一个应用程序,并在该应用程序中使用计时器来更改 WPF C# .NET 中的标签内容。
在计时器的已用事件中,我正在编写以下代码,
lblTimer.Content = "hello";
但它抛出 InvalidOperationException
并给出消息调用线程无法访问此对象,因为不同的线程拥有它。
我正在使用 .NET Framework 3.5 和 WPF 以及 C#。
请帮助我。
提前致谢。
I'm making an application and I'm using a timer in that application to change label content in WPF C# .NET.
In the timer's elapsed event I'm writing the following code
lblTimer.Content = "hello";
but its throwing an InvalidOperationException
and gives a message The calling thread cannot access this object because a different thread owns it.
I'm using .NET framework 3.5 and WPF with C#.
Please help me.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 .NET 4.0,使用 DispatcherTimer 要简单得多。然后,事件处理程序位于 UI 线程中,它可以直接设置控件的属性。
For .NET 4.0 it is much simpler to use a DispatcherTimer. The eventhandler is then in the UI thread and it can set properties of the control directly.
InvokeRequired 在 wpf 中不起作用。
更新另一个线程拥有的 GUI 元素的正确方法是:
在模块级别声明:
这是更新标签的方法:
InvokeRequired doesn't work in wpf.
The proper way the update a GUI element owned by another thread is this :
Declare this on module level :
This is the method to update your label :