我有 wpf UserControl,其中包含一个组合框和一个连续的文本框。目前,在组件之间移动的唯一方法是在它们之间切换,但我希望还能够使用左右箭头键从组合框切换到文本框。
这并不像在 keyup 事件上使用事件处理程序那么简单。
void ComboKeyUp( object sender, KeyEventArgs e )
{
if( e.Key == Key.Right)
{
e.Handled = true;
textbox.Focus();
}
}
...因为尽管事件被报告为已处理,但组合仍会更改值。
有没有办法做到这一点,同时不会破坏组合框中项目的向上/向下选择?
我创建了带有文本框的组合框:
<ComboBox Width="100" Height="25" PreviewKeyDown="ComboboxPreviewKeyDown">
<ComboBox.Items>
<TextBox Text="Item 1"/>
<TextBox Text="Item 2"/>
<TextBox Text="Item 3"/>
</ComboBox.Items>
</ComboBox>
然后添加处理程序:
private void ComboboxPreviewKeyDown(object sender, KeyEventArgs e)
{
Action<FocusNavigationDirection> moveFocus = focusDirection => {
e.Handled = true;
var request = new TraversalRequest(focusDirection);
var focusedElement = Keyboard.FocusedElement as UIElement;
if (focusedElement != null)
focusedElement.MoveFocus(request);
};
if (e.Key == Key.Down)
moveFocus(FocusNavigationDirection.Next);
else if (e.Key == Key.Up)
moveFocus(FocusNavigationDirection.Previous);
}
现在“向上”和“向下”按钮的行为与“Tab”和“Shift+Tab”相同
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)