wpf - 在没有代码隐藏的情况下按下键时将焦点设置在另一个控件上

标签 wpf focus controls

我正在实现类似自动建议控件的功能:我有一个用户控件,其中包含一个 TextBox 和一个 ListBox。当用户输入文本时,我用 System.Windows.Interactivity 行为处理它并用一些值填充 ListBox...

一切正常...但我想让用户能够选择 ListBox 中的项目(即在 ListBox 上设置 Focus >) 当按下向下箭头键时。

我知道可以在代码隐藏 .cs 文件中处理 TextBoxKeyPressDown 事件,但如何避免这种情况?

最佳答案

如果您已经使用了应该不是什么大问题的交互性,只需实现您自己的具有属性 KeyTargetNameTriggerAction确定何时以及要关注什么。在 PreviewKeyDownEventTrigger 中设置它。

示例实现和使用:

<TextBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewKeyDown">
            <t:KeyDownFocusAction Key="Down"
                                  Target="{Binding ElementName=lbx}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>
<ListBox Name="lbx" ItemsSource="{Binding Data}" />
class KeyDownFocusAction : TriggerAction<UIElement>
{
    public static readonly DependencyProperty KeyProperty =
        DependencyProperty.Register("Key", typeof(Key), typeof(KeyDownFocusAction));
    public Key Key
    {
        get { return (Key)GetValue(KeyProperty); }
        set { SetValue(KeyProperty, value); }
    }

    public static readonly DependencyProperty TargetProperty =
        DependencyProperty.Register("Target", typeof(UIElement), typeof(KeyDownFocusAction), new UIPropertyMetadata(null));
    public UIElement Target
    {
        get { return (UIElement)GetValue(TargetProperty); }
        set { SetValue(TargetProperty, value); }
    }

    protected override void Invoke(object parameter)
    {
        if (Keyboard.IsKeyDown(Key))
        {
            Target.Focus();
        }
    }
}

测试它并且它有效,请注意 KeyDown 没有,因为箭头键被拦截并标记为由 TextBox 处理。

关于wpf - 在没有代码隐藏的情况下按下键时将焦点设置在另一个控件上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7124871/

相关文章:

HTML 5 自定义控件

wpf - 从加载项调用 WPF 时 Excel 关闭缓慢

c# - 将触发器值传递给 Wpf 应用程序

wpf - 移动 wpf 中的任何控件

wpf - 在 WPF 和 MVVM 中使用 ObservableCollections

android - 在Android中设置相机对焦区域

JavaFX 2 : How to focus a table row programmatically?

focus - Web 应用程序在没有焦点时可以捕获按键吗?

asp.net - 在asp.net网站上动态加载用户控件(ascx)

c# - asp changepassword控件自定义