32

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();
        }
    }
}
Ben Griswold
  • 17,793
  • 14
  • 58
  • 60

15 Answers15

41

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();
   }
Jon Galloway
  • 52,327
  • 25
  • 125
  • 193
Jim B-G
  • 479
  • 4
  • 3
23
Plugin.Focus(); 

didn't work for me.

Calling

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

From the Load event worked.

rekle
  • 2,375
  • 1
  • 18
  • 9
10

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

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

om.
  • 101
  • 1
  • 2
3

I solved putting in the control constructor:

this.TargetTextBox.Loaded += (o, e) => { this.TargetTextBox.Focus(); };
Smamatti
  • 3,901
  • 3
  • 32
  • 43
Luca
  • 31
  • 1
2

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().

Bill Reiss
  • 3,460
  • 1
  • 19
  • 20
2

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.

Santiago Palladino
  • 3,522
  • 2
  • 26
  • 36
  • Thanks for the suggestion. I hooked up the DispatcherTimer and result is the same. It isn't until I physically take an action (click on the page, for example) is focus set. – Ben Griswold Sep 24 '08 at 17:36
2

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

mike gold
  • 21
  • 1
1

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....

Bryant
  • 8,660
  • 1
  • 33
  • 53
  • Thanks Bryant. I like how you validated using the button click. I'll see if I can't come up with something similar to your MouseMove suggestion. – Ben Griswold Sep 24 '08 at 02:53
1

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

Community
  • 1
  • 1
harryhazza
  • 117
  • 1
  • 4
1

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

See my question here for other ideas.

Community
  • 1
  • 1
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
1

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;
        }
user544583
  • 21
  • 4
  • This works in IE and FF, but not Chrome. I simplified it out as HtmlPage.Plugin.Focus(); someTextBox.UpdateLayout(); someTextBox.Focus(); – Keith Adler Apr 21 '11 at 16:20
0

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

kleopatra
  • 51,061
  • 28
  • 99
  • 211
0

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.

Bill Reiss
  • 3,460
  • 1
  • 19
  • 20
0

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.

Talha Imam
  • 1,046
  • 1
  • 20
  • 22
0

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.

Community
  • 1
  • 1
Matthew Steven Monkan
  • 8,170
  • 4
  • 53
  • 71