我正在实现类似自动建议控件的功能:我有一个用户控件,其中包含一个 TextBox
和一个 ListBox
。当用户输入文本时,我用 System.Windows.Interactivity
行为处理它并用一些值填充 ListBox
...
一切正常...但我想让用户能够选择 ListBox
中的项目(即在 ListBox
上设置 Focus
>) 当按下向下箭头键时。
我知道可以在代码隐藏 .cs 文件中处理 TextBox
的 KeyPressDown
事件,但如何避免这种情况?
最佳答案
如果您已经使用了应该不是什么大问题的交互性,只需实现您自己的具有属性 Key
和 TargetName
的 TriggerAction
确定何时以及要关注什么。在 PreviewKeyDown
的 EventTrigger
中设置它。
示例实现和使用:
<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/