Friday, November 19, 2010

How Do I Set Textbox Focus in Silverlight4.0?

Here is an example to set focus for a text box in Silverlight application.

In Page.xaml

<UserControl x:Class="TextboxFocusTest.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Loaded="UserControl_Loaded" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">        
        <StackPanel Width="150" VerticalAlignment="Center">            
            <TextBox x:Name="UserNameTextBox" IsTabStop="True" />    
        </StackPanel>        
    </Grid>
</UserControl>

In Page.xaml.cs

using System.Windows;
using System.Windows.Controls;
namespace TextboxFocusTest
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
	   System.Windows.Browser.HtmlPage.Plugin.Focus();
           UserNameTextBox.Focus();
        }
    }
}

Happy Coding..Smile

No comments:

Post a Comment