我在多个线程上使用Show.Dialog,但是有一个问题。 从UI线程调用的对话框关闭时, 即使还有一些从另一个线程调用的对话框,MainWindow也会被激活。 为了避免这种情况,我想在UI线程上显示另一个对话框,但是如何可能呢? 或者还有其他方法可以避免这个问题吗?
public partial class CustomMsgBox : Window
{
//this class implements a method that automatically
//closes the window of CustomMsgBox after the designated time collapsed
public CustomMsgBox(string message)
{
InitializeComponent();
Owner = Application.Current.MainWindow;
//several necessary operations...
}
public static void Show(string message)
{
var customMsgBox = new CustomMsgBox(message);
customMsgBox.ShowDialog();
}
}
public class MessageDisplay
{
//on UI thread
public delegate void MsgEventHandler(string message);
private event MsgEventHandler MsgEvent = message => CustomMsgBox.Show(message);
private void showMsg()
{
string message = "some message"
Dispatcher.Invoke(MsgEvent, new object[] { message });
}
}
public class ErrorMonitor
{
//on another thread (monitoring errors)
public delegate void ErrorEventHandler(string error);
private event ErrorEventHandler ErrorEvent = error => CustomMsgBox.Show(error);
private List<string> _errorsList = new List<string>();
private void showErrorMsg()
{
foreach (var error in _errorsList)
{
Application.Current.Dispatcher.BeginInvoke(ErrorEvent, new object[] { error });
}
}
}
当从UI线程调用的CustomMsgBox自动关闭时, 即使仍有一些从监控线程调用的CustomMsgBox,也会激活MainWindow。
答案 0 :(得分:3)
您应该只从UI线程打开Dialog。您可以使用调度程序调用UI-Thread:
// call this instead of showing the dialog direct int the thread
this.Dispatcher.Invoke((Action)delegate()
{
// Here you can show your dialiog
});
您可以简单地编写自己的ShowDialog / Show
方法,然后致电调度员。
我希望我理解你的问题是正确的。