大家好,我是编写 C# 应用程序的新手。
抱歉,如果它太基础了。 我有一个在 Main xaml 中运行的线程,它查询一些信息并更新一个属性。
因此,一旦我检测到该属性设置为“X”,我就需要切换到不同的 XAML View 。
我面临的问题是当我从属性调用开关时,我的应用程序崩溃了。 我认为这与线程有关..
问:如何在检测到属性值更改后立即切换到不同的 XAML View ?
示例代码:
公共(public)部分类 MainWindow : Window {
....
private Thread t;
public static enState dummy;
public enState SetSTATE
{
get
{
return dummy;
}
set
{
dummy = value;
if (dummy == A )
{
var NEWVIEW = new VIEW1();
contentGrid.Children.Add(NEWVIEW); // - crashes in this block
}
}
}
public void startThread()
{
t = new Thread(getInfo);
t.Isbackground = true;
t.start();
}
public void getInfo()
{
while (true)
{
int x = somefunc();
if (x == conditon)
{
SetSTATE = A;
}
Thread.Sleep(1000);
}
}
MainWindow() { startThread(); }
公共(public)部分类 NEWVIEW: UserControl
最佳答案
您不能从后台线程修改集合。您需要显式使用 Dispatcher.BeginInvoke 进行修改:
if (dummy == A )
{
contentGrid.Dispatcher.BeginInvoke(new Action(() =>
{
var NEWVIEW = new VIEW1();
contentGrid.Children.Add(NEWVIEW);
}));
}
关于c# - 当我切换到不同的 XAML 时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18152057/