I've got a small DataForm and I want to set the focus on the first TextBox. I'm using the Novermber 2009 Toolkit. I've named the TextBox and tried using .Focus() from the DataForm's loaded event. I see it get focus for one cursor 'blink' and then it's gone. I'm trying to work out if this is an artefact of the DataForm or something else. Does anyone know if I should be able to do this?
Asked
Active
Viewed 1,921 times
4

AnthonyWJones
- 187,081
- 35
- 232
- 306

serialhobbyist
- 4,768
- 5
- 43
- 65
-
I have the same problem. Created an issue on the codeplex project's page : http://silverlight.codeplex.com/workitem/8365 – Olivier Payen Feb 17 '11 at 11:08
3 Answers
1
A little trick I've used successfully is to subscribe to the Loaded event of the textbox, then in the event handler, I set the focus with code such as this:
private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
TextBox usernameBox = (TextBox)sender;
Dispatcher.BeginInvoke(() => { usernameBox.Focus(); });
}

witters
- 691
- 1
- 7
- 20
1
I tried loads of suggestions e.g. using Dispatcher, UpdateLayout etc etc. floating around on various internet sites and none of them worked reliably for me. In the end I settled on the following:
private bool _firstTime = true;
private void MyChildWindow_GotFocus(object sender, RoutedEventArgs e)
{
if (_firstTime)
{
try
{
var dataForm = MyDataForm;
var defaultFocus = dataForm.FindNameInContent("Description") as TextBox;
defaultFocus.Focus();
}
catch (Exception)
{
}
finally
{
_firstTime = false;
}
}
}
Not pretty I know...but it works. There appears to be a timing issue with using the Focus() method in SL4.

Myles J
- 2,839
- 3
- 25
- 41
-
This worked for me. The key is to set the focus on the correct TextBox on the GotFocus event. – Steve Wranovsky Oct 26 '11 at 04:15
0
Try calling my custom focus setting function (FocusEx).
internal static class ControlExt
{
// Extension for Control
internal static bool FocusEx(this Control control)
{
if (control == null)
return false;
bool success = false;
if (control == FocusManager.GetFocusedElement())
success = true;
else
{
// To get Focus() to work properly, call UpdateLayout() immediately before
control.UpdateLayout();
success = control.Focus();
}
ListBox listBox = control as ListBox;
if (listBox != null)
{
if (listBox.SelectedIndex < 0 && listBox.Items.Count > 0)
listBox.SelectedIndex = 0;
}
return success;
}
}
That should work for you.
Jim McCurdy

Jim McCurdy
- 2,052
- 14
- 14
-
Thanks for the suggestion. I've tried it but it didn't help: I get the same results. The TextBox has the focus briefly, then loses it. If I comment out the .Focus() or, using your code, the .FocusEx() statement, it doesn't get the focus at all, so I know they're working to start with. Something else must be stealing it but I don't know how to work out what it is. – serialhobbyist Jan 13 '10 at 15:05