Question

I am trying to set the initial focus to a control in a Silverlight form. I am trying to use attached properties so the focus can be specified in the XAML file. I suspect that the focus is being set before the control is ready to accept focus. Can anyone verify this or suggest how this technique might be made to work?

Here is my XAML code for the TextBox

<TextBox x:Name="SearchCriteria" MinWidth="200" Margin ="2,2,6,2" local:AttachedProperties.InitialFocus="True"></TextBox>

The property is defined in AttachedProperties.cs:

public static DependencyProperty InitialFocusProperty = 
    DependencyProperty.RegisterAttached("InitialFocus", typeof(bool), typeof(AttachedProperties), null);

public static void SetInitialFocus(UIElement element, bool value)
{
    Control c = element as Control;
    if (c != null && value)
        c.Focus();
}

public static bool GetInitialFocus(UIElement element)
{
    return false;
}

When I put a breakpoint in the SetInitialFocus method, it does fire and the control is indeed the desired TextBox and it does call Focus.

I know other people have created behaviors and such to accomplish this task, but I am wondering why this won't work.

Was it helpful?

Solution

You're right, the Control isn't ready to recieve focus because it hasn't finished loading yet. You can add this to make it work.

public static void SetInitialFocus(UIElement element, bool value)
{
    Control c = element as Control;
    if (c != null && value)
    {
        RoutedEventHandler loadedEventHandler = null;
        loadedEventHandler = new RoutedEventHandler(delegate
        {
            // This could also be added in the Loaded event of the MainPage
            HtmlPage.Plugin.Focus();
            c.Loaded -= loadedEventHandler;
            c.Focus();
        });
        c.Loaded += loadedEventHandler;
    }
}

(In some cases, you may need to call ApplyTemplate as well according to this link)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top