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.
<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
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:
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
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...