user3595338
user3595338

Reputation: 757

How to set focus on listbox item?

I have a defined list box like this:

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

And I want to set focus directly to an item in the listbox.

If I do this:

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

The focus is set to the entire listBox, so if I press arrow down to move the selection to the item below, I have to press the arrow twice. First time the focus jumps from the entire listBox to the first item, and then when I can press the arrow again and the selection finally jumps down.

I want to set the focus directly to that first item, so I don't have to press the arrow twice.

Upvotes: 12

Views: 31251

Answers (3)

Noor E Alam Robin
Noor E Alam Robin

Reputation: 286

var listBoxItem =  
   (ListBoxItem)listBox
     .ItemContainerGenerator
       .ContainerFromItem(listBox.SelectedItem);

listBoxItem.Focus();

Upvotes: 22

Jon C
Jon C

Reputation: 1

You can't use Focus.() on a listbox item. However you can select items which is pretty much the same thing as you are looking to do. listbox.SelectedIndex = 0;

Upvotes: 0

markhc
markhc

Reputation: 679

Here's a similar (if not equal) question Setting focus on a ListBox item breaks keyboard navigation

And the code (I don't mess with WPF so I can't guarantee this works, but it was accepted on the thread I linked so it might):

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

Upvotes: 2

Related Questions