9

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

看法:

<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
}
4

3 回答 3

13

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

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

如果您的 ListBox 包含ListBoxItems 以外的其他内容,您可以使用它lbActions.ItemContainerGenerator.ContainerFromIndex(lbActions.SelectedIndex)来获取自动生成的ListBoxItem.


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

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

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

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        lbActions.Focus();
        lbActions.SelectedIndex = 0;
        ((ListBoxItem)lbActions.SelectedItem).Focus();
    }
于 2010-02-08T18:38:59.757 回答
1

您也可以在 XAML 中轻松完成此操作。请注意,这只会设置逻辑焦点。

例如:

<Grid FocusManager.FocusedElement="{Binding ElementName=itemlist, Path=SelectedItem}">
    <ListBox x:Name="itemlist" SelectedIndex="1">
        <ListBox.Items>
            <ListBoxItem>One</ListBoxItem>
            <ListBoxItem>Two</ListBoxItem>
            <ListBoxItem>Three</ListBoxItem>
            <ListBoxItem>Four</ListBoxItem>
            <ListBoxItem>Five</ListBoxItem>
            <ListBoxItem>Six</ListBoxItem>
        </ListBox.Items>
    </ListBox>
</Grid>
于 2011-09-20T12:27:46.317 回答
-1

ListBox控件似乎有两个级别的Focus:ListBox本身和ListBoxItem。就像 Heinzi 所说,直接为 ListBoxItem 设置 Focus 将避免您必须在方向键上单击两次才能遍历所有 ListBoxItems 的情况。

经过几个小时的工作,我发现了这一点,现在它在我的 APP 上完美运行。

于 2020-07-07T23:45:57.327 回答