And*_*mes 3 wpf xaml focus keyboard-events
我有一个带有两个文本框的WPF视图.当用户像Tab一样击中键盘上的向下箭头时,我想自动将焦点从第一个文本框向前移动到第二个文本框.
似乎我应该能够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>
Run Code Online (Sandbox Code Playgroud)
有人对这个有经验么?好像我应该能够使用InputBindings或EventTrigger来做到这一点.
我正在使用MVVM,这是一个View问题.我可以放弃一点代码隐藏(作为一个视图关注,这是合理的),但它只是感觉我错过了一些东西.
我希望有人能提出更优雅的东西,但这就是我到目前为止所拥有的.它不是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>
Run Code Online (Sandbox Code Playgroud)
事件处理程序(根本没有错误处理):
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3823 次 |
| 最近记录: |