32
votes

In my Silverlight application, I can't seem to bring focus to a TextBox control. On the recommendation of various posts, I've set the IsTabStop property to True and I'm using TextBox.Focus(). Though the UserControl_Loaded event is firing, the TextBox control isn't getting focus. I've included my very simple code below. What am I missing? Thanks.

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="RegularTextBox" IsTabStop="True" />    
        </StackPanel>        
    </Grid>
</UserControl>

Page.xaml.cs

using System.Windows;
using System.Windows.Controls;

namespace PasswordTextboxTest
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            RegularTextBox.Focus();
        }
    }
}
15
It depends on the browser!JOG
That may sound obvious but check if your textbox is disabled before trying to focus. focus() will only work on enabled controls.Fortune

15 Answers

41
votes

I found this on silverlight.net, and was able to get it to work for me by adding a call to System.Windows.Browser.HtmlPage.Plugin.Focus() prior to calling RegularTextBox.Focus():

   private void UserControl_Loaded(object sender, RoutedEventArgs e)
   {        
      System.Windows.Browser.HtmlPage.Plugin.Focus();
      RegularTextBox.Focus();
   }
23
votes
Plugin.Focus(); 

didn't work for me.

Calling

 Dispatcher.BeginInvoke(() => { tbNewText.Focus();});

From the Load event worked.

10
votes

thanks Santiago Palladino Dispatcher worked for me perfectly. What I am doing is:

this.Focus(); then Dispatcher.BeginInvoke(() => { tbNewText.Focus();});

3
votes

I solved putting in the control constructor:

this.TargetTextBox.Loaded += (o, e) => { this.TargetTextBox.Focus(); };
2
votes

Are you sure you're not really getting focus? There's a known bug in Beta 2 where you'll get focus and be able to type but you won't get the caret or the border. The workaround is to call UpdateLayout() on the textbox right before you call Focus().

2
votes

I would try adding a DispatcherTimer on the UserLoaded event that executes the Focus method a few milliseconds after the whole control has loaded; maybe the problem is there.

2
votes

I also needed to call

Deployment.Current.Dispatcher.BeginInvoke(() => myTextbox.Focus());

interestingly this call is happening inside an event handler when I mouseclick on a TextBlock, collapse the TextBlock and make the TextBox Visible. If I don't follow it by a dispatcher.BeginInvoke it won't get focus.

-Mike

1
votes

You code to set the focus is correct since if you add a button that calls the same code it works perfectly:

<StackPanel Width="150" VerticalAlignment="Center">
    <TextBox x:Name="RegularTextBox" IsTabStop="True" />
    <Button Click="UserControl_Loaded">
        <TextBlock Text="Test"/>
    </Button>
</StackPanel>

So I'm assuming this is something to do with Focus() requiring some kind of user interaction. I couldn't get it to work with a MouseMove event on the UserControl, but putting a KeyDown event to set the focus works (although the template doesn't update to the focused template).

Width="400" Height="300" Loaded="UserControl_Loaded" KeyDown="UserControl_KeyDown">

Seems like a bug to me....

1
votes

For out-of-browser apps the System.Windows.Browser.HtmlPage.Plugin.Focus(); doesn't exist.

See my question here for other ideas.

1
votes

It works for me in SL4 and IE7 and Firefox 3.6.12

Final missing "piece" which made focus to work (for me) was setting .TabIndex property

        System.Windows.Browser.HtmlPage.Plugin.Focus();
        txtUserName.IsTabStop = true;
        txtPassword.IsTabStop = true;

        if (txtUserName.Text.Trim().Length != 0)
        {
            txtPassword.UpdateLayout();
            txtPassword.Focus();
            txtPassword.TabIndex = 0;
        }
        else
        {
            txtUserName.UpdateLayout();
            txtUserName.Focus();
            txtUserName.TabIndex = 0;
        }
1
votes

My profile is not good enough to comment on @Jim B-G's answer but what worked for me was to add a handler for the Loaded event on the RichTextBox and inside that handler add

System.Windows.Browser.HtmlPage.Plugin.Focus();
<YourTextBox>.UpdateLayout()
<YourTextBox>.Focus();

However, it only worked on IE and FF. To get it work on Chrome and Safari, scroll to the bottom of this

0
votes

I forgot one thing...I haven't found a way to force focus to your Silverlight application on the page reliably (it will work on some browsers and not on others).

So it may be that the Silverlight app itself doesn't have focus. I usually trick the user into clicking a button or something similar before I start expecting keyboard input to make sure that the silverlight app has focus.

0
votes

I also ran into this problem, but it had arisen from a different case than what has been answered here already.

If you have a BusyIndicator control being displayed and hidden at all during your view, controls will not get focus if you have lines like

Dispatcher.BeginInvoke(() => { myControl.Focus();}); 

in the load event.

Instead, you will need to call that line of code after your BusyIndicator display has been set to false.

I have a related question here, as well as a solution for this scenario.

0
votes

Indeed an annoying beheviour. I found a simple straightforward solution:

(VB code)

    Me.Focus()
    Me.UpdateLayout()

    Me.tbx_user_num.Focus()
    Me.tbx_user_num.UpdateLayout()

Each element here is essential, as per my project at least (VB2010 SL4 OutOfBrowser).

Credit to : http://www.dotnetspark.com/kb/1792-set-focus-to-textbox-silverlight-3.aspx

0
votes

None of the above answers worked for me directly, what i did is that I added this event in in the MainPage() constructor:

this.Loaded += new RoutedEventHandler(MainPage_Loaded);

And handled it as follows:

   void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        System.Windows.Browser.HtmlPage.Plugin.Focus();
        RegularTextBox.Focus();
    }

My Silverlight version is 4.