C# 在单独线程中的 WPF 应用程序中设置标签内容时出现问题
我有一个包含标签(player1)的窗口。我还有一个类,可以在线程内的后台异步收集数据。收集数据后,我想更改标签的内容。由于标签是由 UI 创建的,并且我尝试从另一个线程编辑它,因此我尝试使用 Dispatcher。然而,经过几个小时的尝试和不同的例子,我无法让它工作。在下面最简单的形式中,方法dispatchP1在从我的主窗口调用时更改了player1的值。但是,从我的班级调用时它不起作用。另外,我没有收到错误或任何信息。
public delegate void MyDelegate();
public void dispatchP1()
{
player1.Dispatcher.BeginInvoke(new MyDelegate(p1SetContent));
}
public void p1SetContent()
{
player1.Content = "text";
}
任何帮助将不胜感激。
I have a window that contains a label (player1). I also have a class that gathers data asynchronously in the background inside a thread. When that data has been gathered, I want to changed the content of my label. Since the label was created by the UI and I'm trying to edit it from another thread, I tried using Dispatcher. However, after hours of trying and different examples, I can't get it to work. In it's most simple form below, the method dispatchP1 changes the value of player1 when called from my main window. However, it doesn't work when called from my class. Also, I don't receive an error or anything.
public delegate void MyDelegate();
public void dispatchP1()
{
player1.Dispatcher.BeginInvoke(new MyDelegate(p1SetContent));
}
public void p1SetContent()
{
player1.Content = "text";
}
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码看起来并不是特别有问题 - 但 WPF 有吞掉异常的习惯。在 App.xaml 中,您可以处理 DispatcherUnhandledException 事件并在其中放置一个断点以确定它是否真的引发异常。
That code doesn't seem particularly problematic - but WPF has a habit of swallowing exceptions. In your App.xaml, you can handle the event DispatcherUnhandledException and put a breakpoint in there to determine if it is really throwing an exception or not.
您知道可以使用匿名代表吗?
You know you can use anonymous delegates?