Friday, August 14, 2009

Silverlight – Set focus to the silverlight control

When loading a web page which hosts a Silverlight application, I noticed that before interacting with the Silverlight application the user was required to first click on the application so that it got input focus. It was immediately obvious that I would need to use a small piece of java script to set the focus to the control. This is how I got it to work.

1. Give the <object> element in the web page an ID
2. Pass the ‘onLoad’ parameter on the Silverlight application assigning a JavaScript function that will focus to application in the browser.

<object id="silverlightControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/DragSnapDemo.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="onLoad" value="silverlightControlHost_Load" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object>


3. Finally write the JavaScript function that is called when the Silverlight application has be loaded



function silverlightControlHost_Load(sender, args) 
{
var control = document.getElementById("silverlightControl");
control.focus();
}


The trick here is that the JavaScript function is only called once the Silverlight application has been fully downloaded and loaded into the browser. To achieve this I used the onLoad event of the application.

No comments:

Post a Comment