本文介绍了调用线程必须是STA,因为许多UI组件都需要此WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 WPF工具包提供的MessageBox.而且我得到了错误
I am using the MessageBox provided by WPF Toolkit. And I get the error
调用线程必须是STA,因为许多UI组件都需要
new Thread(new ThreadStart(delegate
{
MessageBox.Show("Opeartion could not be completed. Please try again.","Error",MessageBoxButton.OK,MessageBoxImage.Error);
})).Start();
在这种情况下如何设置ApartmentState
How can I set the ApartmentState in this case
我正在尝试使用WPF Toolkit的MessageBox控件显示无模式的MessageBox.到目前为止,我拥有的代码如下:
I am trying to display a modeless MessageBox using MessageBox control of WPF Toolkit.So far the code I have is as follows:
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();
}
}
推荐答案
// 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);
});
}
这篇关于调用线程必须是STA,因为许多UI组件都需要此WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!