How can I determine when my StackPanel lost focus, from inside the UserControl that contains it?
I have a Silverlight UserControl, and it contains a StackPanel which, in turn, contains some UserControls in it. I would like to be able to determine when the user clicks/tabs outside of the outermost StackPanel (i.e. when the StackPanel loses focus), and I would like to be able to handle it from inside my UserControl. Does anyone have any suggestions on how I might accomplish that?
When one of the components lost focus, I tried dispatching a thread that would look to see if any controls within the main UserControl gained focus next, which would then tell me if I'm still inside my control. Trouble is, I was already on the UI thread, so the Dispatcher executed my action immediately, while I was still in the process of handling LostFocus. So, this didn't work.
Something else I tried involved using the FocusManager and determining if the control with focus was a child of my StackPanel. This didn't work because Get开发者_开发问答FocusedElement() returned the element whose focus I was in the process of losing.
Does anyone have any other ideas? Any help is appreciated.
This might not be the most elegant solution, but why don't you catch the OnLostFocus event on the StackPanel itself? In the handler, raise another event that your parent user control listens to. This way, you don't have to worry about dispatches or threads. Keeps it simple.
精彩评论