How to find the focused ListBoxItem in WPF

Published 05 September 07 04:10 PM | andarno 

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.

Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# szurgot said on September 5, 2007 12:53 PM:

And here I thought I was the only person dealing with this. I haven't actually done up the work, but I think you have to keep track of the focused item as the selection changes in order to be able to offer it up when the user wants it.

# Andrew Whiddett said on March 17, 2008 9:00 PM:

Yes you can find the Framework Element that has the focus, but you have to walk the whole visual tree.

Andrew

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

Search

This Blog

Interesting blogs

Related sites

Syndication

Page view tracker