在
WPF应用程序中,我想实现以下似乎不能直接起作用的行为:
从主窗口(Window1),用户打开非模态窗口(Window2),并且该非模态窗口可以显示模态对话框(Window3).
问题是,只要显示模态对话框,当用户关闭对话框时,主窗口就会在后台消失(假设有其他应用程序的窗口打开).
我使用Window.Owner和Window.Show()/ Window.ShowDialog()的方式有什么不对,它是一个bug还是它不支持的东西?
以下简单的WPF应用程序演示了此行为:
public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Button_Click(object sender,RoutedEventArgs e) { Window2 win = new Window2(); win.Owner = this; win.Show(); } } public partial class Window2 : Window { public Window2() { InitializeComponent(); } private void Button_Click(object sender,RoutedEventArgs e) { Window3 win = new Window3(); win.Owner = this; win.ShowDialog(); } private void btnClose_Click(object sender,RoutedEventArgs e) { this.Close(); } } public partial class Window3 : Window { public Window3() { InitializeComponent(); } private void btnClose_Click(object sender,RoutedEventArgs e) { this.Close(); } }
XAML Window1:
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1"> <Button Click="Button_Click">Show non-modal window</Button> </Window>
XAML Window2:
<Window x:Class="WpfApplication1.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window2"> <StackPanel> <Button Click="Button_Click">Show modal dialog</Button> <Button Name="btnClose" Click="btnClose_Click">Close</Button> </StackPanel> </Window>
XAML Window3:
<Window x:Class="WpfApplication1.Window3" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window3"> <Button Name="btnClose" Click="btnClose_Click">Close</Button> </Window>
解决方法
WPF中的Microsoft
confirms this as a bug:
This isn’t a regression from prevIoUs releases so it doesn’t make the bar to be fixed for this version of the product. We’ll look into this for a future release.
In the meantime,this can be worked around by activating the owner window when the child window is closing.
Sample code:
public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void NonModalButtonClick(object sender,RoutedEventArgs e) { new Window1 { Owner = this }.Show(); } private void ModalButtonClick(object sender,RoutedEventArgs e) { new Window1 { Owner = this }.ShowDialog(); } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if (this.Owner != null) { this.Owner.Activate(); } } }
(请注意,解决方法将始终将主窗口置于前景中,这可能与预期的行为不同)