在 WPF 应用程序中,我想实现以下似乎并不简单的行为:
用户从主窗口 ( Window1
) 打开一个非模态窗口 ( Window2
),该非模态窗口可能会显示一个模态对话框 ( Window3
)。
问题是,每当显示模式对话框时,当用户关闭对话框时,主窗口就会在后台消失(假设有其他应用程序的窗口打开)。
Window.Owner
我使用和Window.Show()
/的方式有什么问题Window.ShowDialog()
吗,是错误还是根本不支持?
以下简单的 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>
更新:修复了代码中的复制和粘贴错误。这是 .NET 3.5 SP1,以防万一。