How to set focus on a list item?

I have a specific list:

var listBox = new ListBox();
listBox.Items.Add(1);        
listBox.Items.Add(2);
listBox.Items.Add(3);

And I want to set the focus directly on the item in the list.

If I do this:

listBox.SelectedIndex = 0;
listBox.Focus();

The focus is on the entire Box list, so if I click the down arrow to move the selection one item below, I have to double-click the arrow. The first time, the focus jumps from the entire Box list to the first item, and then when I can click the arrow again, and the selection finally jumps down.

I want to set the focus directly to this first element, so I don’t need to press the arrow twice.

+4
source share
2 answers
var listBoxItem = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(listBox.SelectedItem);
listBoxItem.Focus();
+7
source

( ) ListBox

( WPF, , , , , ):

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

Source: https://habr.com/ru/post/1543787/


All Articles