views:

1394

answers:

2

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.

+1  A: 

You are on the right track. You need to handle for two test cases:
1. Setting the focus in the browser. 2. Setting the focus out of the browser.

Your code you that you showed in the Loaded event will work perfectly fine out of the browser. All that is necessary is to refactor it to handle both cases:

private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
{
    if (App.current.IsRunningOutOfBrowser)
    {
        textBox1.Focus();
    }
    else
    {
        System.Windows.Browser.HtmlPage.Plugin.Focus();
        textBox1.Focus();
    }
}

That should do the trick for you.

mattduffield
i haven't tried this again yet, but the problem was it didnt work for the Loaded event for out of browser. remember this is a child window - not just a 'regular control'
Simon_Weaver
+1  A: 

I had to use your GotFocus way for Silverlight 3 application written in IronPython when I wanted to set focus in ChildWindow.

Lukas Cenovsky