【问题标题】:WPF main window put in background after closing a child window关闭子窗口后,WPF主窗口置于后台
【发布时间】:2014-03-14 10:42:04
【问题描述】:

我开发了一个示例 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);
        }
    }
}

当用户点击按钮时:

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

我做了以下动作:

  • 我已经启动了应用程序。操作后截取的屏幕截图:

  • 我点击了按钮。显示 R1 窗口。操作后截取的屏幕截图:

  • 我已关闭 R1 窗口。主窗口已自动置于后台。操作后截取的屏幕截图:

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

【问题讨论】:

  • 尝试设置childWindow.Owner = Application.Current.MainWindow;

标签: wpf window


【解决方案1】:

无法告诉您为什么将其发送到后台,但将其保持在前台并聚焦的方法是使其成为子窗口的所有者,并在子窗口位于时调用父窗口的 Window.Focus() 方法关闭...

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

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

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多