开发者

How to set focus on textbox when showing a child window

Upon starting up my silverlight app a child window appears to prompt the user to login. Within in the window I have a username textbox that I want to be focused so that the user can begin typing without focusing it with the mouse first.

This seems like it should work:

public partial class LoginForm : ChildWindow
{
    public LoginForm()
    {
     开发者_开发知识库   InitializeComponent();
    }

    private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
    {
        txtUsername.Focus();
    }
}

I noticed that the Load event happens before the window is rendered which might be the problem, however I don't see an event handler for Rendered or similar.

Edit: Forgot to mention this application is running in the browser.


You need set TabIndex on txtUsername with lower value than other controls on that child window.


Try this:

public partial class LoginForm : ChildWindow
{
    public LoginForm()
    {
        InitializeComponent();
         Loaded+=LoginFormLoaded;
    }
       private void LoginFormLoaded(object sender, RoutedEventArgs e)
    {
         txtUsername.Focus();
         Loaded-=LoginFormLoaded;
    }

}

update: You can also add your event on your TextBox. the textbox has a Loaded event too. If you use this event, you are sure that the TextBox is loaded.


If you are running the application in the browser make sure that the silverlight plugin has focus before calling the focus method of the control.

private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
{         
    HtmlPage.Plugin.Focus();
    txtUsername.Focus();
}

This works on most browsers except I couldn't get it to work on Safari.


Here is something I use:

public partial class LoginForm : ChildWindow 
{ 
    public LoginForm() 
    { 
        InitializeComponent(); 
        Loaded += (s, e) =>
        {
           txtUsername.Focus();
        }; 
    }
} 

And in XAML set your TabIndex to 1


For some reason that I do not have time to figure out, the Child Window in the Silverlight SDK opens, animates, and the focus moves to some unknown place. Most of the solutions suggested on this thread do not work for me because the control receives focus briefly (you can see the focus hit the text box) and then the focus moves to somewhere else (I am guessing that the storyboard on the ChildWindow template has something to do with that). So, I figured out this work around that is actual code that has been implemented and has been proven to work:

public NewChildWindow()
{
    InitializeComponent();
    this.GotFocus += NewChildWindow_GotFocus; 
}

private void NewChildWindow_GotFocus(object sender, RoutedEventArgs e)
{
    this.GotFocus -= NewChildWindow_GotFocus;
    txtBoxToFocusOn.Focus();
}


Make your textbox TabIndex="0" and in its Loaded event do the "YourtxtBox.Focus()"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜