【问题标题】:WPF minimized owned windows should stay minimized, if Parent is minimized and then restored如果父级被最小化然后恢复,WPF 最小化的拥有的窗口应该保持最小化
【发布时间】:2022-07-20 21:17:23
【问题描述】:

我有一个主窗口和一个子窗口。子窗口的所有者是主窗口。子窗口不是对话框。我在子窗口的构造函数中使用了如下代码:

this.Owner = Application.Current.MainWindow;
this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
this.ShowInTaskbar = false;

我设置了this.ShowInTaskbar = false,因为我希望子窗口在最小化时显示在屏幕底部(而不是在任务栏中)。当我最小化主窗口时,子窗口也应该最小化(这是有效的)。但是当子窗口已经最小化时,如果我最小化并恢复主窗口,子窗口也会恢复。如果子窗口已经最小化,我希望它保持最小化。

【问题讨论】:

  • 这可能是设计使然。想想记事本查找窗口...
  • 如何使“子窗口在最小化时显示在屏幕底部(而不是在任务栏中)”?您如何管理这种状态?
  • emoacht,这是默认的 WPF 行为。您所要做的就是设置 ShowInTaskbar = false。

标签: c# wpf windows


【解决方案1】:

此行为是设计使然,但您可以通过在父级的 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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多