by mheydt
3.
May 2009 22:27
>
If you've ever worked with Silverlight applications that accept user input, you've probably dealt with setting focus to various controls. In that case you may know this already. If you haven't then this should definitely save you some hassles.
There is an issue with Silverlight having their controls receive initial focus. As an example, take a look at the following silverlight application. This is the first page of the application and it has a text box that I would like to have the focus currently in:

I've actually called the TextBox.Focus() method in the load event of this UserControl, but it doesn't have the focus. What gives?
Well, the problem turns out to be that the Silverlight object in the HTML itself has not received the input focus from the browser, and hence the control in the Silverlight app do not receive the focus as it is somewhere else in the browser. As a matter of fact if you click anywhere on the Silverlight app (lets say in the gray areas) the browser will give the Silverlight control the focus, which then gives it to the specified text box.
So how do we enforce that the Silverlight application receive focus from the browser when it is started? That turns out to be quite simple and involves just a couple lines of JavaScript in the web page serving the Silverlight application:

What you do is add the OnPluginLoaded event property on the silverlight control, and put the script shown as in the head tag. Net time (and every time from now on), your control will get the focus when the application starts:

Yeah!