移动焦点以响应XAML中的键盘事件
问题描述:
我有一个带有两个文本框的WPF视图。当用户像Tab一样按下键盘上的向下箭头时,我想自动将焦点从第一个文本框向前移动到第二个文本框。移动焦点以响应XAML中的键盘事件
看来我应该能够100%声明地做到这一点,但由于某种原因,我认为这样做的命令似乎没有做任何事情。这是我第一次尝试不起作用:
<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);
}
+1简单哇!手势对我来说是新事物 – 2009-10-26 20:28:45