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

Nic*_*olo 2 wpf controls focus

我正在实现类似自动提示控件的东西:我有一个包含a TextBox和a 的用户控件ListBox.当用户输入文本时,我正在处理System.Windows.Interactivity行为并填写ListBox一些值...

一切正常......但我想使用户能够选择的项目ListBox(即设置FocusListBox按下向下箭头键时).

我知道可以处理代码隐藏.cs文件中的KeyPressDown事件TextBox但是我该如何避免这种情况?

H.B*_*.B. 5

如果您已经使用交互性应该不会有太大的问题,只是实现自己TriggerAction拥有的属性KeyTargetName对indentify时间和内容重点.将它设置EventTrigger为for PreviewKeyDown.

示例实施和使用:

<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}" />
Run Code Online (Sandbox Code Playgroud)
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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

测试它并且它工作,请注意,KeyDown因为箭头键被拦截并标记为由TextBox处理.