سؤال

When my Silverlight page loads, I want to set focus on a control. Simple problem with a not-so-obvious solution.

I tried the following with no luck. The page loads but my control does not have focus.

public MainPage()
{
    InitializeComponent();

    if( !DesignerProperties.IsInDesignTool )
    {
        // some init code goes here...

        this.Loaded += ( s, e ) =>
            {
                this.InitFocus();
            };
    }
}

private void InitFocus()
{
    this.PropNumTextBox.Focus();
}
هل كانت مفيدة؟

المحلول

The solution is to use System.Windows.Browser.HtmlPage.Plugin.Focus(). When I call this prior to calling Focus on my initial control, it works as expected. The correct code looks as follows:

public MainPage()
{
    InitializeComponent();

    if( !DesignerProperties.IsInDesignTool )
    {
        // init code here...

        this.Loaded += ( s, e ) =>
            {
                this.InitFocus();
            };
    }
}

private void InitFocus()
{
    // this call is necessary to initialize focus on page load
    System.Windows.Browser.HtmlPage.Plugin.Focus();
    this.PropNumTextBox.Focus();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top