3

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を使用していますが、これはビューの問題です。少しコードビハインドに立ち寄ることもできますが(ビューの問題なので、これは合理的です)、何かが足りないように感じます。

4

1 に答える 1

5

誰かがこれよりもエレガントなものを思いつくことを願っていますが、これは私がこれまでに持っているものです。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);
}
于 2009-10-26T20:23:50.130 に答える