【问题标题】:The calling thread must be STA, because many UI components require this WPF [duplicate]调用线程必须是 STA,因为许多 UI 组件需要这个 WPF [重复]
【发布时间】:2012-05-24 07:27:28
【问题描述】:

我正在使用WPF Toolkit 提供的MessageBox。我得到了错误

调用线程必须是STA,因为很多UI组件都需要这个

new Thread(new ThreadStart(delegate
{
    MessageBox.Show("Opeartion could not be completed. Please try again.","Error",MessageBoxButton.OK,MessageBoxImage.Error);
})).Start();

在这种情况下如何设置 ApartmentState

编辑: 我正在尝试使用 WPF Toolkit 的 MessageBox 控件显示无模式的 MessageBox。 到目前为止,我的代码如下:

void SomeFunction()
{
// calls to some UI, and processing and then

var th = new Thread(new ThreadStart(delegate
                                        {
                                           MessageBox.Show("Opeartion could not be completed. Please try again.",
                                                "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                        }));

                                        th.SetApartmentState(ApartmentState.STA);
                                        th.Start();
                                    }
}

【问题讨论】:

    标签: c# wpf sta apartment-state


    【解决方案1】:
    // enable unit test to mock a dispatcher
    var dispatcher = Dispatcher.CurrentDispatcher;
    if (Application.Current != null)
    {
        // use the application dispatcher if running from the software
        dispatcher = Application.Current.Dispatcher;
    }
    
    if (dispatcher != null)
    {
        // delegate the operation to UI thread.
        dispatcher.Invoke(
            delegate
            {
                MessageBox.Show("Opeartion could not be completed. Please try again.","Error",MessageBoxButton.OK,MessageBoxImage.Error);
            });
    }
    

    【讨论】:

      【解决方案2】:

      已编辑

      根据MSDN WPF 中存在内置的模态消息框,但如果你想使用无模式消息框,那么你必须创建自定义窗口然后显示它。 从自定义无模式 MessageBox 创建、显示和返回值并不是很困难。 可以看this链接

      只为消息框使用不同的线程是不明智的。无论如何,您可以通过以下方式设置单身公寓状态...

        Thread th = new Thread(new ThreadStart(delegate
        {
          MessageBox.Show("Opeartion could not be completed. Please try again.", "Error",MessageBoxButtons.OK,MessageBoxImage.Error);
        }));
      
        th.ApartmentState = ApartmentState.STA;
        th.Start();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多