Technology: Silverlight 3.0
Problem: I want to close a Popup when a Custom Control that contains the popup losses focus.
Considerations:
LostFocus is a Routed Event
This means that if a child triggers a lostFocus event, it will bubble up to the parent. I don’t think this makes too much sense because if a focus changed from a child to another child of the same parent, then the parent should not have a LostFocus event triggered (because the focus is still in one of its children)…but that is how it works.
LostFocus and the Popup control
When one of the Children is a popup, the LostFocus event won’t bubble up to Popup the container (This happens for the LostFocus and for other routed events as well).
Example: If I click on tst2.1, and then on tst2.2, the event LostFocus will be triggered for the stack panel SP2, but it won’t trigger for SP1.
Solution:
There are two things to address, 1) The fact that the LostFocus event will not get to the parent control, and 2) The fact that lostFocus being triggered does not mean that the control lost focus (but one of its children did).
To solve 1), have a panel container inside the Popup, and register to the lostFocus event in that control. You know that all the lostFocus for the popup children will trigger the container LostFocus.
To solve 2), in the LostFocus event for your control, check if the current focused element (FocusMager.GetFocusedElement) is inside your control. You can do this using VisualTreeHelper class.