Wpf 移动焦点以响应XAML中的键盘事件
我有一个WPF视图和两个文本框。当用户点击键盘上的向下箭头时,我想自动将焦点从第一个文本框向前移动到第二个文本框,就像Tab一样 看起来我应该能够100%声明式地完成这项工作,但由于某些原因,我认为可以完成这项工作的命令似乎什么也做不到。这是我的第一次尝试,但没有成功:Wpf 移动焦点以响应XAML中的键盘事件,wpf,xaml,focus,keyboard-events,Wpf,Xaml,Focus,Keyboard Events,我有一个WPF视图和两个文本框。当用户点击键盘上的向下箭头时,我想自动将焦点从第一个文本框向前移动到第二个文本框,就像Tab一样 看起来我应该能够100%声明式地完成这项工作,但由于某些原因,我认为可以完成这项工作的命令似乎什么也做不到。这是我的第一次尝试,但没有成功: <StackPanel> <TextBox Text="Test"> <TextBox.InputBindings> <!-- I rea
<StackPanel>
<TextBox Text="Test">
<TextBox.InputBindings>
<!-- I realize ComponentCommands.MoveFocusDown doesn't work...
This is just an example of what I've tried and the type
of answer I'm looking for -->
<KeyBinding Key="Down" Command="ComponentCommands.MoveFocusDown" />
</TextBox.InputBindings>
</TextBox>
<TextBox></TextBox>
</StackPanel>
有没有人有这方面的经验?似乎我应该能够使用InputBindings或EventTrigger来实现这一点
我正在使用MVVM,这是一个视图问题。我可以顺便加入一些代码隐藏(作为一个视图关注点,这是合理的),但感觉好像我遗漏了一些东西。我希望有人能想出比这更优雅的东西,但这就是我目前所拥有的。它不是100%XAML,但至少是通用的 此示例显示了一个包含两个按钮和两个文本框的窗口。向下箭头在它们之间循环聚焦 我希望这有帮助
<Window x:Class="WPF_Playground.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
>
<Window.CommandBindings>
<CommandBinding Command="ComponentCommands.MoveFocusDown" Executed="CommandBinding_Executed"/>
</Window.CommandBindings>
<StackPanel KeyboardNavigation.DirectionalNavigation="Cycle">
<Button>Tester</Button>
<Button>Tester2</Button>
<TextBox Text="Test">
<TextBox.InputBindings>
<KeyBinding Command="ComponentCommands.MoveFocusDown" Gesture="DOWN" />
</TextBox.InputBindings>
</TextBox>
<TextBox Text="Test2">
<TextBox.InputBindings>
<KeyBinding Command="ComponentCommands.MoveFocusDown" Gesture="DOWN" />
</TextBox.InputBindings>
</TextBox>
</StackPanel>
</Window>
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
UIElement senderElement = sender as UIElement;
UIElement focusedElement = FocusManager.GetFocusedElement(senderElement) as UIElement;
bool result = focusedElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
Debug.WriteLine(result);
}