Reputation: 687
I have a customized message box in my WPF application. Problem is : This message box is not showing when I called it in a class that is not derived from Window. There is no compilation error. References are added properly.
I coundn't call any UI components in this class.
There occurs an exception when debugging: "The calling thread must be STA because many UI components require this"
Upvotes: 1
Views: 166
Reputation: 1330
I had the same problem, the problem was that when we create our custom MessageBox, it derives from UI components like Windows maybe, and then when we try to create and show our custom MessageBox from a thread which we have created by code in our application (meaning a background thread) we get the error:
"The calling thread must be STA because many UI components require this".
As "mottukutty" has commented to his own problem, the solution is to use application's Dispatcher to show our custom MessageBox, something like:
public partial class MessageBox : Window
{
private static MessageBox _messageBox;
public static MessageBoxResult Show(string message, MessageBoxType type,
string okText = null, string yesText = null, string noText = null)
{
Application.Current.Dispatcher.Invoke(show);
void show()
{
_messageBox = new MessageBox(message, type, okText, yesText, noText);
_messageBox.ShowDialog();
}
return _messageBox.Result;
}
}
Upvotes: 5