1

在我的桌面应用程序中,我想在 BackgroundWorker 中打开视图以显示提醒。但是当我尝试打开视图时,它给了我以下错误。 “调用线程必须是 STA,因为很多 UI 组件都需要这个。” 并且 stackTrace 是

 at System.Windows.Input.InputManager..ctor()
   at System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
   at System.Windows.Input.KeyboardNavigation..ctor()
   at System.Windows.FrameworkElement.FrameworkServices..ctor()
   at System.Windows.FrameworkElement.EnsureFrameworkServices()
   at System.Windows.FrameworkElement..ctor()
   at System.Windows.Controls.Control..ctor()
   at System.Windows.Window..ctor()
   at MahApps.Metro.Controls.MetroWindow..ctor()

谁能有解决方案?

4

1 回答 1

0

你可以这样做:

    private BackgroundWorker _BgWorker;


    public Window1()
    {
        InitializeComponent();

        _BgWorker = new BackgroundWorker();
        _BgWorker.DoWork += new DoWorkEventHandler(bgw_DoWork);
        _BgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
    }

void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        ///your code to get the data from database...
    }

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      //you code to open a view
    }

在已完成的 Runworker 中使用这个

Thread Messagethread = new Thread(
        new ThreadStart(delegate()
        {
            DispatcherOperation DispacherOP = frmMassenger.Dispatcher
                .BeginInvoke(DispatcherPriority.Normal, new Action(
                    delegate()
                    {
                        frmMassenger.Show();
                    }
            ));
        } ));
        Messagethread.Start();

稍后您使用以下方法将线程与主线程连接起来:

Thread.join(userthread);

希望这会帮助你。

于 2013-06-26T09:37:38.547 回答