Getting a notification when focus changes in Silverlight 4?

好久不见. 提交于 2019-12-12 21:27:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!