Lars Holm Jensen's Code Blog

Just another WordPress codeblog on C#, Silverlight and all things .NET

Archive for the ‘focused’ tag

FocusHelper

with one comment

Here is a little helper class I use when implementing tab navigation in Silverlight. When FocusHelper.Start() is called at application startup it simply creates a timer which attempts to give the focused element a red border and a slightly red background. When I say attempts it’s because themes and styles may prevent the changes from showing. I have often found it helpful, because it is almost never clear which element in Silverlight has the focus. Notice that the functionality is disabled if your browser’s zoom is different from 100%.

public static class FocusHelper
{
    public static void Start()
    {
        focusBorderBrush = new SolidColorBrush(Colors.Red);
        focusBackground = new SolidColorBrush(Colors.Red);
        focusBackground.Opacity = 0.1;
 
        focusTimer = new Timer(new TimerCallback((o) =>
        {
            try
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    object temp = null;
 
                    if (System.Windows.Application.Current.Host.Content.ZoomFactor==1)
                        temp = FocusManager.GetFocusedElement();
 
                    if (temp != lastFocus)
                    {
                        if (temp is Control)
                        {
                            //Give the last control back its original color
                            if (lastFocus != null)
                            {
                                lastFocus.BorderBrush = lastBrush;
                                lastFocus.BorderThickness = lastThickness;
                                lastFocus.Background = lastBackground;
                            }
 
                            lastFocus = temp as Control;
                            lastBrush = lastFocus.BorderBrush;
                            lastThickness = lastFocus.BorderThickness;
                            lastBackground = lastFocus.Background;
 
                            lastFocus.BorderBrush = focusBorderBrush;
                            lastFocus.BorderThickness = new Thickness(1);
                            lastFocus.Background = focusBackground;
                        }
                    }
                });
            }
            catch
            {
            }
 
        }), null, 0, 100);
    }
 
    private static System.Threading.Timer focusTimer;
    private static Control lastFocus = null;
    private static Thickness lastThickness;
    private static Brush lastBrush;
    private static Brush lastBackground;
    private static Brush focusBorderBrush;
    private static Brush focusBackground;
}

Written by larsholm

December 16th, 2009 at 6:46 pm