3

我有一个带有两个文本框的 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>

有人对这个有经验么?似乎我应该能够使用 InputBindings 或 EventTrigger 来做到这一点。

我正在使用 MVVM,这是一个视图问题。我可以加入一些代码隐藏(作为一个视图问题,这是合理的),但感觉就像我错过了一些东西。

4

1 回答 1

5

我希望有人想出比这更优雅的东西,但这就是我到目前为止所拥有的。它不是 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);
}
于 2009-10-26T20:23:50.130 回答