c# - 当具有(键盘)焦点的子项被移除时,将(键盘)焦点设置为父容器
问题描述
我在画布中有两个按钮(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 消失但画布不变为绿色 我希望画布变为绿色
解决方案
您可以手动将焦点移至 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));
// ...
}
}
同样通过这种方式,您可以将焦点从窗口移动到画布。
推荐阅读
- c++ - 从注册表中检索已注销用户的 sid
- android - layout-land Resources$NotFoundException: 资源 ID #0x7f0b007b
- system-verilog - 断言失败,实例名称不是合法的右值 [7.1(IEEE)]
- python - 如何为模型中的排序添加字段长度?
- c# - 我可以在不同的操作系统上运行具有非核心依赖项的 .net 核心应用程序吗?
- php - cPanel上的Laravel黑屏
- kubernetes - Kubelet 未启动:崩溃并退出状态:255/n/a
- c# - 将 Animator 附加到克隆 GameObject
- python - 优化从每个可评估为列表的字符串列表中制作平面列表
- amazon-web-services - AWS Elasticsearch - 建议为 m4.large.elasticsearch 实例创建多少个分片和副本