Search code examples
c#wpflistboxfocusvisualstates

Detect when a ListBoxItem is in the SelectedUnfocused state


Problem

I want my Listbox to UnselectAll() whenever the user clicks anywhere outside of it.

What I've done so far

The following code works fine for all clicks inside the application:

    private void ListBox_LostFocus(object sender, RoutedEventArgs e)
    {
        ((ListBox)sender).UnselectAll();
    }

Clicking anything outside of the Listbox causes it to lose focus and then unselect everything inside. Great.

However, if I click on something outside the application main window, I do not get a LostFocus event from the ListBox or the ListBoxItem. Instead, the ListBoxItem goes into the SelectedUnfocused state. As far as I can tell, there is no way to detect that this has happened, short of subscribing to the storyboard.Completed event of the SelectedUnfocused visual state storyboard, or listening for Window.Activated/Deactivated events and then trickling them down through the UI. I feel like I'm missing something obvious and I'd like to avoid that level of hackery if possible.

Question

Clearly, WPF is capable of detecting this situation - it puts the control in the right visual state - so is there some clean way for me to do the same?


Solution

  • Use the LostKeyboardFocus event. There is a difference between LostFocus and LostKeyboardFocus.

    For the details, see this question, as it may help answer your question.