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

标签 c# xaml

大家好,我是编写 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/

相关文章:

c# - 表达式树可能不包含赋值运算符?

c# - 使用迭代器编写自定义 IEnumerator<T>

c# - 将大型 SQL 查询移至 Excel

Silverlight Treeview 内联 HierarchicalDataTemplate 绑定(bind)问题

wpf - 取决于 DataContext 的条件框架元素

c# - Azure存储表逐行删除键

c# - Visual Studio 代码自动完成

c# - 如何在 c#/xaml metro 应用程序中标记时间线时将书签放在 slider 上

xaml - UWP X :Bind and Design Time Data

c# - 使用 richtextbox 的运行作为 itemscontrol