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?

4
  • ListBoxItem has IsKeyboardFocusWithin and IsSelected properties so you can create MultiTrigger that does what you need Commented May 7, 2015 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. Commented May 7, 2015 at 19:11
  • If not you can also add a check directly to the window for losing focus. Commented May 7, 2015 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. Commented May 7, 2015 at 19:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is exactly what I was looking for. Knew I was missing something obvious :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.