简体   繁体   中英

Setting initial focus to a control in a Silverlight form using attached properties

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM