Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A post about Silverlight Focusing Issue

0.00/5 (No votes)
22 Feb 2011 1  
Silverlight Focusing Issue
As a developer or designer, making data entry simpler for users is our job. One of the most used techniques in this process is giving focus to a control. Because, when a user navigates to a page, then user can start data entry without clicking to a control in the page. This technique is also available in Silverlight applications.

Issue Demonstration



Let’s demonstrate focusing technique in a Silverlight Application.

Firstly, we are adding 2 textbox control in a stackpanel and then giving focus to second textbox control.

XML
<Stackpanel>
    <TextBox Width="208" x:name="txtOne" Margin="0,10,0,0"/>
    <textbox Width="208" x:name="txtTwo" Margin="0,10,0,0"/>
</Stackpanel>


Code - Behind


C#
public MainPage()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    txtTwo.Focus();
}

When we run our Silverlight application, we will see an unexpected behavior.




If we click somewhere in the page, second textbox will take focus as expected. But why do we have to click? It seems an unnecessary action.

The exact reason behind this behavior is so obvious. Because our Silverlight plugin does not have focus. We provide giving focus to plugin by clicking the page. After this process, Silverlight could behave as expected. But how can we solve this problem ?

Solutions

Actually, we have 2 different solution techniques for his problem. First one is giving focus to Silverlight plugin using JavaScript. The other one is doing the same operation using Silverlight.

First Solution

We can give focus to Silverlight plugin using this JavaScript code like below:

JavaScript
var SlElement = document.getElementById('silverlightControlHost');
 if (SlElement)
     SlElement.focus(); 

Second Solution

In this solution, we will use HtmlPage type that is in System.Windows.Browser namespace. As you know, we can make some HTML DOM operations using this type. At this point, we will use static Focus method of HtmlPage’s Plugin property.

Final Code-Behind

C#
public MainPage()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
 
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    System.Windows.Browser.HtmlPage.Plugin.Focus();
    txtTwo.Focus();
} 

When we run this application, we can see expected behavior like below:



Hope this helps...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here