简体   繁体   English

关闭 Window 关闭并关注父 Window WPF

[英]Close Window on Deactivated and Focus on Parent Window WPF

In my WPF Project, I have two Windows and from the main parent Window I call the child like so:在我的 WPF 项目中,我有两个Windows和来自主要父母 Window 我这样称呼孩子:

PARENT家长

ChildWindow win = new ChildWindow();
win.Owner = this /* (Parent window) */;
win.Show();

CHILD孩子

private void Window_Deactivated(object sender, EventArgs e)
{
    this.Close();
    owner.Activate();
    // Also tried: owner.Focus();
}

And I want it so that when the user clicks on the Parent window, it closes the child window and focuses on the parent.我想要这样当用户点击父 window 时,它会关闭子 window 并专注于父。 I have made a Deactivated event on the child which does Close();我在执行Close();的孩子身上做了一个Deactivated事件。 but on clicking the parent window, it closes the window but hides the parent one as well so it is not focused, but under all other applications.但是在单击父 window 时,它会关闭 window 但也会隐藏父级,因此它不是集中的,而是在所有其他应用程序下。 How can I make it so that it doesn't?我怎样才能让它不呢? I have tried having a owner.Activate();我试过拥有一个owner.Activate(); after it is closed but same thing happens.关闭后但同样的事情发生。

This is a small video of what is happening: https://vimeo.com/485043728 .这是正在发生的事情的一个小视频: https://vimeo.com/485043728 I would like to get the same effect when clicking on another window (where the parent window is visible) but when the user clicks back to the parent window, it hides it.我想在单击另一个 window(父 window 可见)时获得相同的效果,但是当用户单击返回父 window 时,它会隐藏它。

You can do something like this for your desired result.你可以为你想要的结果做这样的事情。

MainWindow.xaml主窗口.xaml

<Window x:Class="StackOverflow.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:StackOverflow"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Height="50" Width="100" Content="Open Child" Click="Button_Click"/>
    </Grid>

MainWindow.xaml.cs主窗口.xaml.cs

using System.Windows;

namespace StackOverflow
{
    public partial class MainWindow : Window
    {
        private Window _child;

        public MainWindow()
        {
            InitializeComponent();
            _child = new Window();
            _child.LostKeyboardFocus += _child_LostFocus;
        }

        private void _child_LostFocus(object sender, RoutedEventArgs e)
        {
            _child.Hide();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _child.Show();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM