关闭子窗口后,WPF主窗口放入后台

use*_*666 3 wpf window

我开发了一个示例WPF项目.
这是主窗口的代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;

namespace MainWindowInBackground
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window l_hostWindow = new Window()
            {
                Owner = System.Windows.Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Content = "Test"
            };

            l_hostWindow.Show();

            Window l_hostWindow2 = new Window()
            {
                Owner = System.Windows.Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Content = "Test 2"
            };

            l_hostWindow2.Show();
            l_hostWindow2.Close();

            //MessageBox.Show(this, "MessageBox", "MessageBox", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当用户单击按钮时:

  1. 创建并显示窗口R1
  2. 创建并显示窗口R2
  3. R2窗口关闭

我做了以下行动:

  • 我已经启动了该应用程序.操作后截图:

在此输入图像描述

  • 我点击了按钮.显示R1窗口.操作后截图:

在此输入图像描述

  • 我关闭了R1窗口.主窗口已自动放入后台.操作后截图:

在此输入图像描述

有人可以解释一下为什么主窗口已经自动放入后台以及如何避免它?预先感谢您的帮助

Dea*_*uga 5

无法告诉你为什么它被发送到后台但是将它保持在前台并且专注的方法是使它成为子窗口的所有者并Window.Focus()在子窗口关闭时调用父窗口的方法...

public ChildWindow()
{
    InitializeComponent();
    Owner = Application.Current.MainWindow;
}

private void ChildWindow_OnClosed(object sender, WindowClosedEventArgs e)
{
    if (Owner == null) return;
    Owner.Focus();
}
Run Code Online (Sandbox Code Playgroud)