I'm looking for a way to automatically set the initial focus on a Silverlight UserControl to a specific control. I have a login page with a user name textbox and I'd like to have it so that as soon as the user goes to the page their cursor is already positioned and waiting in the username textbox instead of having to make them click the box.
I tried calling .Focus in the UserControl's Loaded event but with no success. Anyone know how to do this?
If you want this code:
work in all browsers, you must set the tabIndex for element with id="Xaml1".
Sorry for my English :)
If you want to do it in a PRISM or MVVM way (get rid of the code-behind code), you can implement a behavior. In my case I focus the view in the username field if it's empty and in the password if it's set (hence the 2 parameters).
My implementation:
I just did a quick test and it looks like this solve the problem in the browser too!
How to set focus on TextBox in Silverlight 4 out-of-browser popup
I whipped up a quick SL3 app and it is difficult to have the initial focus go to the UserControl let alone to a control within the Silverlight control.
However, see if this solution solves this issue for you. You'll have to use a little JavaScript.
Here's the code for reference:
Once your SL control has focus, you can further set the focus to a specific control using something like:
where uxLogin is defined in XAML as: