【发布时间】:2013-03-15 05:37:34
【问题描述】:
我正在开发 WPF 应用程序。我在MainWindow.xaml 中有一个名为“Status_label”的标签。我想从不同的类(signIn.cs)更改它的内容。
通常我能够做到这一点
var mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
mainWin.status_lable.Content = "Irantha signed in";
但我的问题是,当我尝试通过 signIn.cs 类中的不同线程访问它时,它会给出错误:
The calling thread cannot access this object because a different thread owns it.
我可以使用Dispatcher.Invoke(new Action(() =>{.......... 或其他方式解决这个问题吗?
编辑: 我将从不同的类以及单独的线程中调用此标签更改操作
MainWindow.xaml
<Label HorizontalAlignment="Left" Margin="14,312,0,0" Name="status_lable" Width="361"/>
SignIn.cs
internal void getStudentAttendence()
{
Thread captureFingerPrints = new Thread(startCapturing);
captureFingerPrints.Start();
}
void mySeparateThreadMethod()
{
var mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
mainWin.status_lable.Dispatcher.Invoke(new Action(()=> mainWin.status_lable.Content ="Irantha signed in"));
}
line var mainWin 返回错误The calling thread cannot access this object because a different thread owns it.
请指导我,
谢谢
【问题讨论】:
-
为什么这被否决了?
-
也许,因为这个问题已经被回答了一百次了。一些“谷歌搜索”将为您提供适当的解决方案。
标签: wpf dispatcher mainwindow