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.