views:

293

answers:

1

I have a Silverlight DataGrid of which I need to check if it has Focus. I know there is a method to set Focus and an event for GotFocus but can't see anyhting for checking if it has focus.

Any Ideas ?

+3  A: 

Hi,

AFAIK there is no direct method or property to check if it has focus, but you should be able to use the FocusManager.GetFocusedElement().

If you then define a extension method, you should be able to call MyDataGrid.HasFocus():

public static class ControlExtensions
{
    public static bool HasFocus(this Control aControl)
    {
        return System.Windows.Input.FocusManager.GetFocusedElement() == aControl;
    }
}

[edited: I did test it now:] However there is catch: the call GetFocusedElement() can return the current focused cell within the DataGrid. So in that case the HasFocus will return false.

To be able to check if the DataGrid or one of its cells are focused, we can adapt our extension method like this

public static class ControlExtensions
{
    public static bool HasFocus(this Control aControl, bool aCheckChildren)
    {
        var oFocused = System.Windows.Input.FocusManager.GetFocusedElement() as DependencyObject;
        if (!aCheckChildren)
            return oFocused == aControl;
        while (oFocused != null)
        {
            if (oFocused == aControl)
                return true;
            oFocused = System.Windows.Media.VisualTreeHelper.GetParent(oFocused);
        }
        return false;
    }
}

Hope this helps a bit?

Tjipke
Thanks - I'll give it a go.
cyberbobcat
Well I hope you see I edited a bit...
Tjipke
Yes, that helps - thanks again.
cyberbobcat
@TjipkeI'm having a similar problem, but you solution doesn't work with me - GetFocusedElement() requires a DependcyObject as parameter. Did you try the source you posted?
Christian Hubmann
Yes I did try my source :-)The silverlight version of GetFocusedElement doesn't need that parameter (see: http://msdn.microsoft.com/en-us/library/cc190472(VS.95).aspx), however the WPF version does. Are you trying it in WPF? In that case you don't need this code you can just use DataGrid.IsFocused
Tjipke