将焦点设置在 ListBox 项上会中断键盘导航 [英] Setting focus on a ListBox item breaks keyboard navigation

查看:11
本文介绍了将焦点设置在 ListBox 项上会中断键盘导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以编程方式选择 ListBox 项目后,需要按向下向上键 两次 移动选择.有什么建议吗?

After selecting ListBox item programmatically it is needed to press downup key two times to move the selection. Any suggestions?

查看:

<ListBox Name="lbActions" Canvas.Left="10" Canvas.Top="10"
               Width="260" Height="180">
        <ListBoxItem Name="Open" IsSelected="true" Content="Open"></ListBoxItem>
        <ListBoxItem Name="Enter" Content="Enter"></ListBoxItem>
        <ListBoxItem Name="Print" Content="Print"></ListBoxItem>
</ListBox>

代码:

public View()
{
   lbActions.Focus();
   lbActions.SelectedIndex = 0; //not helps
   ((ListBoxItem) lbActions.SelectedItem).Focus(); //not helps either
}

推荐答案

不要将焦点设置到 ListBox... 将焦点设置到选定的 ListBoxItem.这将解决需要敲击两次键盘"的问题:

Don't set the focus to the ListBox... set the focus to the selected ListBoxItem. This will solve the "two keyboard strokes required" problem:

if (lbActions.SelectedItem != null)
    ((ListBoxItem)lbActions.SelectedItem).Focus();
else
    lbActions.Focus();

如果您的 ListBox 包含的不是 ListBoxItems,您可以使用 lbActions.ItemContainerGenerator.ContainerFromIndex(lbActions.SelectedIndex) 来获取自动生成的 ListBoxItem.

If your ListBox contains something else than ListBoxItems, you can use lbActions.ItemContainerGenerator.ContainerFromIndex(lbActions.SelectedIndex) to get the automatically generated ListBoxItem.

如果您希望在 窗口初始化 期间发生这种情况,您需要将代码放入 Loaded 事件中,而不是放入构造函数中.示例 (XAML):

If you want this to happen during window initialization, you need to put the code in the Loaded event rather than into the constructor. Example (XAML):

<Window ... Loaded="Window_Loaded">
    ...
</Window>

代码(基于您问题中的示例):

Code (based on the example in your question):

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        lbActions.Focus();
        lbActions.SelectedIndex = 0;
        ((ListBoxItem)lbActions.SelectedItem).Focus();
    }

这篇关于将焦点设置在 ListBox 项上会中断键盘导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆