All Blog Posts

Why Can I Not Focus?

Recently a coworker and I created a Silverlight Business Application for a new project.  This project comes with a Login screen which is very nice. After a few times starting the application I found myself having to click in the username field which was quite annoying. After some research we found code to set focus within our XAML UI element:

        protected override void OnNavigatedTo(NavigationEventArgs e)

This worked once I was logged in for other fields, but my cursor still didn't focus on the username field when the application loaded. We then noticed that once the Login page received focus the userName field received focus. It appeared that in the browser the Silverlight application did not have focus on load.

We fixed this by applying some javascript in the HTML of the page hosting the Silverlight application. This javascript is called by adding "onload='javascript:page_loaded();" on the body tag.

        function page_loaded() {

Another way to set focus to the Silverlight application is to call the HtmlPage.Plugin.Focus() method in the code behind. Here is what this looks like in code. (Thanks to Keith M. for providing this tip!)

        void LoginScreen_Loaded(object sender, RoutedEventArgs e)

Now our application loads and focus is set to the userName field on the login screen.