How to find the focused ListBoxItem in WPF

Andrew Arnott

One would expect that the WPF ListBox control would have some kind of FocusedIndex property to find out which item has the keyboard focus (and that dashed border around it) — but it’s not there.  It seems the workaround requires a few lines of code, which I present here.

ListBox.SelectionMode = Single

In a ListBox’s default mode that allows exactly one item to be selected, you can quite easily query the SelectedIndex property instead, since the focused item is always also the one selected item. 

ListBox.SelectionMode = Multiple || Extended

But when you allow multiple selections, finding the focused item is not as simple.  It may not even be selected. 

There is a ListBoxItem.IsFocused boolean property.  If you’re not using data-binding (you probably should be) you can just iterate through ListBox.Items and break out when you find where ListBoxItem.IsFocused == true.

If you are using data-binding, then the ListBox.Items collection is your data-bound objects rather than ListBoxItems.  You have to get to your ListBoxItem instances another way:

for (int i = 0; i < listBox1.Items.Count; i++) {
    object yourObject = listBox1.Items[i];
    ListBoxItem lbi = (ListBoxItem)listBox1.ItemContainerGenerator.ContainerFromItem(yourObject);
    if (lbi.IsFocused) {
        MessageBox.Show("Item at index " + i.ToString() + " has the focus.");
        break;
    }
}

So where are we at?

Even with these tricks, if the focus isn’t on the ListBox at all, there’s no programmatic way (that I can find anyway) to find out which ListBoxItem would have focus once the ListBox received focus again.

0 comments

Discussion is closed.

Feedback usabilla icon