Setting focus on a ListBox item breaks keyboard navigation

淺唱寂寞╮ 提交于 2019-11-29 06:39:29

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();

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


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();
    }
Anil Vangari

You can do this easily in XAML too. Please note that this will set logical focus only.

For example:

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!