views:

45

answers:

1

Hello,

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 GetFocusedElement() returned the element whose focus I was in the process of losing.

Does anyone have any other ideas? Any help is appreciated.

A: 

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.

j0rd4n
Well, I tried that also. Trouble is, all the children inside the StackPanel bubble up their LostFocus events. So, you may still be inside the StackPanel, but the OnLostFocus handler fires. That's where I tried using the FocusManager to determine if we were still inside the StackPanel, and you know how that turned out =/ Plus, I'd like to keep the functionality within the UserControl as it needs to be reusable... though, at this point, I'll take any solution.
Anna Savarin
Are you checking the 'object sender' parameter passed into the event handler for OnLostFocus? Use the 'is' operator to see if it is a StackPanel type. If it is, check it's element name to see if it is the parent StackPanel. Only raise the outer event if it is.
j0rd4n
Actually, it turns out I was wrong about the FocusManager. It does give me the next focused element while the previous element is losing focus. My control has templated UserControls in it, so I have to walk the tree, find parents, and determine if they belong to the current UserControl that way -- kind of like you're saying. However, as far as your solution, checking if the sender is the StackPanel doesn't cut it since the sender is one of the child controls, so looking for the parent is necessary. In addition, I don't believe you can mark the Focus event as Handled. It will bubble.
Anna Savarin
I appreciate your help!
Anna Savarin