首页 > 解决方案 > 当具有(键盘)焦点的子项被移除时,将(键盘)焦点设置为父容器

问题描述

我在画布中有两个按钮(Focusable=true)我使用 Tab 键选择一个按钮并按 Enter 删除我想要(键盘)焦点返回画布的按钮,但它转到窗口

演示:MainWindow.xaml

<Window x:Class="WpfApplication1.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:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <Style TargetType="Button">
                <Setter Property="Background" Value="Red" />
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocused" Value="True">
                        <Setter Property="Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
            <Style TargetType="Canvas">
                <Setter Property="Background" Value="Red" />
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocused" Value="True">
                        <Setter Property="Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <Canvas Name="Canvas" Focusable="True">
            <Button Click="RemoveSelf">Button 1</Button>
            <Button Canvas.Left="100" Click="RemoveSelf">Button 2</Button>
        </Canvas>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System.Windows;

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

        private void RemoveSelf(object sender, RoutedEventArgs e)
        {
            Canvas.Children.Remove((UIElement)sender);
        }
    }
}

当应用程序启动时,一切都是红色的。按下 TAB 后,画布变为绿色 再次按下 TAB,按钮 1 变为绿色,画布变为红色 按 ENTER,按钮 1 消失但画布不变为绿色 我希望画布变为绿色

标签: c#wpfxaml

解决方案


您可以手动将焦点移至 Canvas:

Canvas.Focus();

在您的按钮回调中:

private void RemoveSelf(object sender, RoutedEventArgs e)
{
    Canvas.Children.Remove((UIElement)sender);
    Canvas.Focus();
}

更新:UIElement.MoveFocus您可以使用代码隐藏中的方法 将焦点移至下一个元素:

private void RemoveSelf(object sender, RoutedEventArgs e)
{
    if (sender is UIElement element)
    {
        element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        // ...
    }
}

同样通过这种方式,您可以将焦点从窗口移动到画布。


推荐阅读