当我切换到不同的XAML时,应用程序崩溃

时间:2013-08-09 17:09:36

标签: c# xaml

嗨,我是编写C#应用程序的新手。

很抱歉,如果它太基本了。 我在Main xaml中运行了一个线程,它查询一些信息并更新属性。

因此,一旦我检测到该属性设置为“X”,我需要切换到不同的XAML视图。

我遇到的问题是当我从属性调用开关时,我的应用程序崩溃了。 我认为这与线程有关..

Qn:一旦检测到属性值发生变化,如何切换到不同的XAML视图?

示例代码:

public partial class 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(); }

}


公共部分类NEWVIEW:UserControl

1 个答案:

答案 0 :(得分:1)

您无法从后台线程修改集合。您需要显式使用Dispatcher.BeginInvoke进行修改:

if (dummy == A )
{
    contentGrid.Dispatcher.BeginInvoke(new Action(() =>
    {
        var NEWVIEW = new  VIEW1();
        contentGrid.Children.Add(NEWVIEW);
    }));
}