如何使 WPF 弹出窗口不隐藏在主应用程序后面? [英] How to make WPF pop-up windows not be hidden behind main application?

查看:49
本文介绍了如何使 WPF 弹出窗口不隐藏在主应用程序后面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WPF 应用程序中,我有用于弹出窗口实例的按钮.

In a WPF application, I have buttons which pop up instances of windows.

  • 我点击第一个按钮,第一个窗口在主应用程序的前面正确弹出.
  • 我点击第二个按钮,第二个窗口在主应用程序的前面正确弹出.但是,第一个窗口现在移动到主应用程序的后面.这是令人困惑和意外的,因为它通常位于主应用程序的中间,因此它似乎消失了,直到用户移动主应用程序发现它隐藏在后面.
  • I click the first button and the first window pops up correctly in front of the main application.
  • I click the second button and the second window pops up correct in front of the main application. However, the first window now moves behind the main application. This is confusing and unexpected since it is often in the middle of the main application and thus seems that it disappears until the user moves the main application to find it hiding behind.

这是XAML:

<Window x:Class="TestPopupFix.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="600" Width="800">
    <StackPanel>
        <Button Content="Open first popup" Click="Button_OpenFirst"/>
        <Button Content="Open second popup" Click="Button_OpenSecond"/>
    </StackPanel>
</Window>

这是背后的代码:

private void Button_OpenFirst(object sender, RoutedEventArgs e)
{
    Window window = new Window();
    TextBlock tb = new TextBlock();
    tb.Text = "This is the first window.";
    window.Content = tb;
    window.Width = 300;
    window.Height = 300;
    window.Show();
}

private void Button_OpenSecond(object sender, RoutedEventArgs e)
{
    Window window = new Window();
    TextBlock tb = new TextBlock();
    tb.Text = "This is the second window.";
    window.Content = tb;
    window.Width = 300;
    window.Height = 300;
    window.Show();
}

当我弹出新窗口时,我必须怎样做才能使主应用程序保持在最靠后的位置?

推荐答案

要在视觉层次结构中排列窗口,您必须将子窗口的 Owner 属性设置为父窗口.

To arrange windows in a visual hierarchy you have to set the Owner property of the child window to the parent window.

您可以阅读有关所有者的更多信息MSDN 上的属性.

You can read more about the Owner property on MSDN.

你应该把你的代码改成类似这样的:

You should change your code into something similar to this:

Window parentWindow;

private void Button_OpenFirst(object sender, RoutedEventArgs e)
{
  this.parentWindow = new Window();
  this.parentWindow.Owner = this;
  this.parentWindow.Show();
}

private void Button_OpenSecond(object sender, RoutedEventArgs e)
{
  Window childWindow = new Window();
  childWindow.Owner = this.parentWindow;
  childWindow.Show();
}

这篇关于如何使 WPF 弹出窗口不隐藏在主应用程序后面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆