Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus on TextBox in Silverlight 4 out-of-browser popup

I have a simple ChildWindow popup in Silverlight 4 (beta).

Important: This is an out-of-browser application.

i want to auto set focus on a TextBox control when the window opens.

I've tried a couple things :

The following code doesn't seem to do anything. I don't think the control is ready to be focussed after 'Loading'.

    private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
    {
          textBox1.Focus();
    }

This works, but its klunky.

    private void ChildWindow_GotFocus(object sender, RoutedEventArgs e)
    {
          if (_firstTime == true) {
              textBox1.Focus();
             _firstTime = false;
          }
    }

Isn't there a better way? I always had to do horrible things like this in WinForms but was hoping not to have to anymore.

Note: This similar question is for in browser only. It suggests calling System.Windows.Browser.HtmlPage.Plugin.Focus(); which doesn't work and in fact gives an error when running on Silverlight 4 beta out-of-browser.

like image 294
Simon_Weaver Avatar asked Jan 23 '23 21:01

Simon_Weaver


1 Answers

I was having the same problem in SilverLight 4 (OOB) and I noticed that the tab sequence would set focus to a control that i could not see. What appears to be happening is the focus is being set to your control (first one in the tab sequence) and then for some reason the focus moves to the ContentControl (name ="content"), which (i think) is the parent of the child window.

ContentControl by default has IsTabStop=true. see.... Why would I want IsTabStop set to true on a ContentControl? To set the ContentControl.IsTabStop = false for all ContentControls in your app, add this to your styles.xaml.

   <Style  TargetType="ContentControl" >
         <Setter Property="IsTabStop" Value="false"/>
    </Style>

The same issue happens with the tab sequence on the MainPage. This style will also fix this.

like image 75
tkerwood Avatar answered May 15 '23 17:05

tkerwood