【问题标题】:Move focus in response to keyboard events in XAML移动焦点以响应 XAML 中的键盘事件
【发布时间】:2009-10-26 19:26:19
【问题描述】:

我有一个带有两个文本框的 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,这是一个视图问题。我可以添加一些代码隐藏(作为视图问题,这是合理的),但感觉就像我错过了一些东西。

【问题讨论】:

    标签: wpf xaml focus keyboard-events


    【解决方案1】:

    我希望有人想出比这更优雅的东西,但这是我目前所拥有的。它不是 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 2018-07-18
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2011-04-01
      • 1970-01-01
      相关资源
      最近更新 更多