Question

I am using the method described here to attach a ViewModel ICommand to the LostFocus event of a Combobox, by setting CommandBehavior.RoutedEventName="LostFocus". I expected the event to fire at the same time the binding for UpdateSourceTrigger=LostFocus fired, but this turns out not to be the case.

The selecteditem Binding UpdateSourceTrigger=LostFocus fires whenever the keyboard tabs away, or after the user actually selects an item from the dropdown by clicking (not sure why this causes lostfocus, but at least it fires AFTER a selection is made).

The attached behavior event fires anytime the user clicks on the Combobox. Immediately. If using the keyboard it behaves normally, firing when you tab away from it. However, when using the mouse, the event fires when the control GAINS focus, before the user has even made a selection. Is there any way to make this behave like lostfocus does for the selecteditem?

Edit: I am curious if another answer exists, but I found a way around this problem, by setting up an additional binding. SelectedItem updates by defualt, handling the normal property change notifications, and selectedvalue updates on lostfocus, handling only the command I was trying to run. Binding looks like this:

SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"
                  SelectedValuePath="CM_CUSTOMER_ID"
                  SelectedValue="{Binding Path=CustomerLostFocus, UpdateSourceTrigger=LostFocus}"
Was it helpful?

Solution

You would need to check the OriginalSource of the event arguments for the LostFocus event:

The LostFocus event is a bubbling event. This means that if multiple LostFocus event handlers are registered for a sequence of objects connected by parent-child relationships in the object tree, the event is received by each object in that relationship. The bubbling metaphor indicates that the event starts at the object that directly receives the input condition, and works its way up the object tree. For a bubbling event, the sender available to the event handler identifies the object where the event is handled, not necessarily the object that actually received the input condition that initiated the event. To get the object that initiated the event, use the OriginalSource value of the event's RoutedEventArgs event data.

So for the ComboBox, you may receive events for the various focusable elements inside the ComboBox.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top