0

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?

pfw
  • 237
  • 3
  • 9
  • `ListBoxItem` has [`IsKeyboardFocusWithin`](https://msdn.microsoft.com/en-us/library/system.windows.uielement.iskeyboardfocuswithin(v=vs.110).aspx) and [`IsSelected`](https://msdn.microsoft.com/en-us/library/system.windows.controls.listboxitem.isselected(v=vs.110).aspx) properties so you can create `MultiTrigger` that does what you need – dkozl May 07 '15 at 18:50
  • That doesn't appear to work. If I make a MultiTrigger with those Conditions, I'm not allowed to set IsSelected in the Setters collection. – pfw May 07 '15 at 19:11
  • If not you can also add a check directly to the window for losing focus. – MiltoxBeyond May 07 '15 at 19:12
  • If I understand you correctly, it works as long as you stay in your application, but it does not work, when you change to another application. That seems to me desireable, since when you return to your application, the focus will still be on the ListBox and the user might expect to find the appilcation in the state it was left; until the user clicks anywhere else inside the application. If you really want your described behaviour, I guess you'd need to check for the Window.Activated state. – azt May 07 '15 at 19:19

1 Answers1

1

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.

Community
  • 1
  • 1
Paul
  • 188
  • 1
  • 10
  • Thanks, this is exactly what I was looking for. Knew I was missing something obvious :) – pfw May 08 '15 at 12:50