问题
I'm trying to debug some issues with missing/extra tab stops. Is there some kind of global event that I can attach to so that I can log which element got focus whenever focus changes? Thanks! Here's what I'm doing right now, which works well enough, but I'm still curious as to whether there's another way:
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(0.2);
timer.Tick += onTick;
timer.Start();
// ...
private object LastFocusedElement;
private void onTick(object sender, EventArgs e)
{
object elem = FocusManager.GetFocusedElement();
if(LastFocusedElement != elem)
{
LastFocusedElement = elem;
System.Diagnostics.Debug.WriteLine("+++FOCUS+++ Focus changed to: " + elem + (elem == null ? "" : " (" + elem.GetType().Name + ")"));
}
}
回答1:
You should be able to subscribe to the GotFocus
event for the "top-most" container. I don't see any Handled flag for RoutedEventArgs
so as far as I can tell, it should always reach it
<UserControl ...
GotFocus="UserControl_GotFocus">
<!-- Lots of Nested Controls -->
</UserControl>
private void UserControl_GotFocus(object sender, RoutedEventArgs e)
{
object elem = e.OriginalSource;
System.Diagnostics.Debug.WriteLine("+++FOCUS+++ Focus changed to: " + elem + (elem == null ? "" : " (" + elem.GetType().Name + ")"));
}
回答2:
You should be able to use AddHandler function to hook up an on focus event with your control.
And look at the AddHandler signature, even an event had been handled you should be able to get a notification as well.
来源:https://stackoverflow.com/questions/4964049/getting-a-notification-when-focus-changes-in-silverlight-4