XAMLのキーボードイベントに応答してフォーカスを移動する
-
06-07-2019 - |
質問
2つのテキストボックスを持つWPFビューがあります。ユーザーがTabとまったく同じようにキーボードの下矢印を押すと、最初のテキストボックスから2番目のテキストボックスにフォーカスを自動的に移動させます。
これを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ではありませんが、少なくとも汎用です。
この例は、2つのボタンと2つのテキストボックスがあるウィンドウを示しています。下矢印は、それらの間でフォーカスを循環させます。
これが役立つことを願っています。
<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);
}
所属していません StackOverflow