How Do I Give a Textbox Focus in Silverlight?

前端 未结 15 1705
無奈伤痛
無奈伤痛 2020-12-01 07:49

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

相关标签:
15条回答
  • 2020-12-01 08:05

    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();
       }
    
    0 讨论(0)
  • 2020-12-01 08:05
    Plugin.Focus(); 
    

    didn't work for me.

    Calling

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

    From the Load event worked.

    0 讨论(0)
  • 2020-12-01 08:07

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

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

    0 讨论(0)
  • 2020-12-01 08:08

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

    0 讨论(0)
  • 2020-12-01 08:12

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

    0 讨论(0)
  • 2020-12-01 08:13

    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

    0 讨论(0)
提交回复
热议问题