在wpf中按Tab键时如何在按钮(焦点)之间导航
本文关键字:焦点 导航 之间 按钮 中按 wpf Tab | 更新日期: 2023-09-27 18:17:01
我设置了F1, F3, F7三个按钮。问题是,在按F1或F3之前,必须聚焦按钮…我想在键盘上使用TAB来聚焦按钮。
<Grid Grid.Row="0" Background="#373737">
<StackPanel Orientation="Horizontal" Margin="0,0,0,1">
<Button x:Name="btnPay" FontSize="13" FontWeight="ExtraBold" Margin="0,0,1,0" BorderThickness="0" Width="120" KeyDown="btnPay_KeyDown">
<StackPanel Orientation="Vertical">
<Image Source="/Image/receipt.png" Width="40" Height="40" />
<TextBlock VerticalAlignment="Center" Margin="5,0" Foreground="White">Thanh toán (F1)</TextBlock>
</StackPanel>
</Button>
<Button x:Name="btnClear" FontSize="13" FontWeight="ExtraBold" Margin="0,0,1,0" BorderThickness="0" Width="120" KeyDown="btnClear_KeyDown">
<StackPanel Orientation="Vertical">
<Image Source="/Image/eraser.png" Width="40" Height="40" />
<TextBlock VerticalAlignment="Center" Margin="5,0" Foreground="White">Xóa (F2)</TextBlock>
</StackPanel>
</Button>
</StackPanel>
<Button x:Name="btnLogOut" FontSize="13" FontWeight="ExtraBold" Width="120" Margin="0,0,1,1" BorderThickness="0" KeyDown="btnLogOut_KeyDown"
HorizontalAlignment="Right">
<StackPanel Orientation="Vertical">
<Image Source="/Image/password.png" Width="40" Height="40" />
<TextBlock VerticalAlignment="Center" Margin="5,0" Foreground="White">Log Out (F6)</TextBlock>
</StackPanel>
</Button>
</Grid>
你的变通方法似乎是一个额外的问题,而不是一个解决方案。而不是使用所有按钮的PreviewKeyDown
事件,只需使用一个窗口,并根据按下的键决定要做什么。
窗口:
<Window PreviewKeyDown="Window_PreviewKeyDown">
背后的代码:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
bool handled = true;
if (!Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
{
switch (e.Key)
{
case Key.F1:
{
Play();
break;
}
// ...
case Key.F6
{
LogOut();
break;
}
default:
handled = false;
break;
}
}
else
{
switch (e.Key)
{
case Key.C:
{
Copy();
break;
}
case Key.V:
{
Paste();
break;
}
case Key.Z:
{
Undo();
break;
}
case Key.Y:
{
Redo();
break;
}
default:
handled = false;
break;
}
}
e.Handled = handled;
}
或者(这将是更好的解决方案),您可以将命令实现为ICommand
,并将它们用于输入绑定。
<Window.InputBindings>
<KeyBinding Modifiers="Control" Key="S" Command="{StaticResource Save}"/>
<KeyBinding Modifiers="Control+Shift" Key="S" Command="{StaticResource SaveAs}"/>
<KeyBinding Modifiers="Control" Key="Z" Command="{StaticResource Undo}"/>
<KeyBinding Modifiers="Control" Key="Y" Command="{StaticResource Redo}"/>
<KeyBinding Key="F1" Command="{StaticResource Play}"/>
<KeyBinding Key="F6" Command="{StaticResource LogOut}"/>
</Window.InputBindings>