dia*_*ler 14 c# wpf dialog window modal-dialog
我注意到WPF应用程序中这种非常奇怪的行为.
我有一个MainWindow
,使用Show()
来自显示App.OnStartup
.说MainWindow
可以打开(非模态)SubWindow
,也可以使用Show()
.SubWindow
的Owner
设置为MainWindow
.
何时SubWindow
关闭,MainWindow
再次可见(好).
某些操作可能会导致SubWindow
打开第三个窗口作为模式对话框,使用ShowDialog()
(Owner
设置为SubWindow
).当该模态对话框在a的生命周期中至少打开并关闭一次时SubWindow
,就会发生奇怪的事情.
关闭后SubWindow
,MainWindow
不会进入视野.相反,无论随机窗口后面 MainWindow
映入眼帘.任何人都可以向我解释为什么会发生这种情况,以及如何解决它?
模态对话框是使用正常Window
显示还是使用显示ShowDialog()
的消息框没有区别MessageBox.Show()
.
这是一些重现这个的最小代码.在visual studio中创建一个新的WPF应用程序,并将其粘贴到预先生成的MainWindow.xaml.cs中
然后,按键盘上的一个键只打开一个窗口,关闭它,按预期行为.按两个键,关闭两个键,然后第一个窗口在Visual Studio后面(推测).
public MainWindow()
{
InitializeComponent();
this.PreviewKeyDown += (sender, e) =>
{
if (this.Owner is MainWindow)
{
// we're the SubWindow
MessageBox.Show("I am a modal dialog");
// code below produces the exact same behavior as the message box
//var dialog = new MainWindow();
//dialog.Owner = this;
//dialog.ShowDialog();
}
else
{
// we're the initial MainWindow created by App.
var subWindow = new MainWindow();
subWindow.Owner = this;
subWindow.Show();
}
};
}
Run Code Online (Sandbox Code Playgroud)
Han*_*ant 10
This is a pretty annoying WPF bug, I never did find the flaw in the code that causes it but there's a heckofalot of "gotta figure this out" comments in the source code that deals with focusing. Just a workaround, a less than ideal one, you can solve it by explicitly giving the focus to the owner when the window is closing. Copy/paste this code in your SubWindow class;
protected override void OnClosing(System.ComponentModel.CancelEventArgs e) {
base.OnClosing(e);
if (!e.Cancel && this.Owner != null) this.Owner.Focus();
}
Run Code Online (Sandbox Code Playgroud)