Introduction
In this article we will see how we can set a focus for a TextBox. In some of the project requirement this is required that the TextBox must be Focused when you load the page.
Known Bug in Silverlight 3
You will find Focus method for almost all UI Element in Silverlight. But when you use it directly, it doesn't work. This is because it is a known bug in Silverlight 3.
What we can do is we can have the following approach to achieve it.
Suppose we have the following TextBox as txtName.
<TextBox x:Name="txtName" Width="200" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap" Margin="10,40,0,0"/>
Now when you set focus for this TextBox the Caret should blink when you load the page.
You can achieve this by adding the UpdateLayout method before applying the Focus to the TextBox.
public MainPage()
{
InitializeComponent();
txtName.UpdateLayout();
txtName.Focus();
}
Now when you run the Application you will see the TextBox is set Focus.
If you are trying Navigation Framework there also you can use it but in different place. The frame has the event as OnNavigateTo as follows.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
#region Focusing TextBox
txtName.UpdateLayout();
txtName.Focus();
#endregion
}
Hope this trick helps.
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Pranav ShahPosted May 9, 2014, 7:02 AM
thanx for help
Ashok NeditedPosted Oct 11, 2012, 7:00 AMEdited Oct 11, 2012, 7:01 AM
Follow below instructions ..... it works for Silverlight in Chrome! It's necessary to set tabindex of silverlight object to 0 and also windowless param to true: <object ... tabindex="0"> <param name="windowless" value="true" /> ... </object>
Raju GhoshPosted Feb 21, 2011, 2:51 AM
This code is not working at all.You can try with this.
Raju GhoshPosted Feb 21, 2011, 2:50 AM
This code is not working at all.