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
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();
}
Plugin.Focus();
didn't work for me.
Calling
Dispatcher.BeginInvoke(() => { tbNewText.Focus();});
From the Load event worked.
thanks Santiago Palladino Dispatcher worked for me perfectly. What I am doing is:
this.Focus(); then Dispatcher.BeginInvoke(() => { tbNewText.Focus();});
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().
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....
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