我有一个主窗口和一个子窗口。子窗口的所有者是主窗口。子窗口是而不是对话框。我在子窗口的构造函数中使用了以下代码:
this.Owner = Application.Current.MainWindow;
this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
this.ShowInTaskbar = false;
我设置了this.ShowInTaskbar = false
,因为我希望最小化时子窗口显示在屏幕底部(而不是任务栏中)。当我最小化主窗口时,子窗口也应该最小化(这是有效的)。但是当子窗口已经最小化时,如果我最小化并恢复主窗口,子窗口也在恢复。如果子窗口已经最小化,我希望它保持最小化。
此行为是设计的,但您可以通过在父级的StateChanged
事件中检查子级的WindowState
属性来覆盖它。如果已最小化,则设置一个标志,并在设置标志时将切换到正常时手动最小化子窗口。
在这个示例中,我放置了一个按钮,用于创建和打开一个新的子Window
,并在父类中设置子的属性和事件侦听器。因此,子窗口没有XAML和代码隐藏文件。代码如下:
XAML:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="407,157,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
代码隐藏:
public partial class MainWindow : Window
{
private Window childWindow;
private bool ignoreStateChange = false;
public MainWindow()
{
InitializeComponent();
this.StateChanged += MainWindow_StateChanged;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
childWindow = new Window() { Owner = this, WindowStartupLocation = WindowStartupLocation.CenterOwner, ShowInTaskbar = false };
childWindow.StateChanged += ChildWindow_StateChanged;
childWindow.Show();
}
private void MainWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Normal && childWindow?.WindowState == WindowState.Minimized)
ignoreStateChange = true;
}
private void ChildWindow_StateChanged(object sender, EventArgs e)
{
if (ignoreStateChange)
{
ignoreStateChange = false;
childWindow.WindowState = WindowState.Minimized;
return;
}
}
}