Microsoft Silverlight 2.0 Beta 2 – Setting Initial Focus on Silverlight Control (Textbox)

(The initial discussion was for Silverlight 2.0 Beta 1)

Step #1

Create a dummy textbox for your initial SL XAML and set the following properties as follows:

Opacity="0" IsReadOnly="True" TabIndex="0"

Step #2

In the ‘loaded’ event of your initial SL XAML, paste the following code to the end of that event:

Windows.Browser.HtmlPage.Plugin.Focus()
Dim t As New System.Windows.Threading.DispatcherTimer()
t.Interval = TimeSpan.FromMilliseconds(100)
AddHandler t.Tick, AddressOf t_Tick
t.Start()

Step #3

Add the following Subroutine which includes setting focus on the textbox:

 Private Sub t_Tick(ByVal sender As Object, ByVal e As EventArgs)
    Dim t As System.Windows.Threading.DispatcherTimer = TryCast(sender, System.Windows.Threading.DispatcherTimer)
    t.[Stop]()
    txtUserName.Focus()
End Sub

Warning: Make sure your VB logic does not set focus to any textbox whatsoever prior to the ‘t_Tick’ sub routine setting your textbox of choice first.

Leave a Reply

Your email address will not be published. Required fields are marked *