【发布时间】:2012-03-12 06:53:02
【问题描述】:
我是 WPF 的新手,在我的应用程序中,我想通过导航键(向上/向下箭头键)来保持 Tab 键顺序。所以我在窗口加载事件上迭代网格中的每个控件并添加委托如下
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (UIElement element in gridChild.Children)
{
if (element.GetType() == typeof(TextBox))
{
TextBox tb1 = (TextBox)element;
tb1.PreviewKeyUp += TextBox_KeyDown;
}
else if (element.GetType() == typeof(PasswordBox))
{
PasswordBox tb1 = (PasswordBox)element;
tb1.PreviewKeyUp += TextBox_KeyDown;
}
else if (element.GetType() == typeof(Button))
{
Button tb1 = (Button)element;
tb1.PreviewKeyDown += TextBox_KeyDown;
}
}
}
处理程序正在跟踪
private void TextBox_KeyDown(Object sender, KeyEventArgs e)
{
if (e.Key == Key.Down || (e.Key == Key.Enter && sender.GetType()!=typeof(Button)) )
{
e.Handled = true;
UIElement focusedElement = Keyboard.FocusedElement as UIElement;
if (focusedElement != null)
{
focusedElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
else if (e.Key == Key.Up)
{
e.Handled = true;
UIElement focusedElement = Keyboard.FocusedElement as UIElement;
if (focusedElement != null)
{
focusedElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
}
}
}
当我使用导航键时它运行良好,除了一个问题。问题是当按下按钮上的向上或向下导航键时,它会跳过一个文本框,该文本框按 Tab 顺序排列。我不确定上面的代码有什么问题。请建议我应该怎么做才能通过导航键保持标签顺序。
【问题讨论】:
标签: wpf tabs navigation key