Why does setting focus in the OnNavigatedTo() event not set focus?

I've got this code in a pages OnNavigatedTo() event:

if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
    textBoxGroupName.Focus(FocusState.Programmatic);
}

...but textBoxGroupName does not have focus when the page displays. Why not?

Upvotes: 1

Views: 662

Answers (2)

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17481

Only controls that are contained within the GroupBox control can be selected or receive focus. Seems like you are not using GroupBox correctly.

From MSDN

The complete GroupBox itself cannot be selected or receive focus. For more information about how this control responds to the Focus and Select methods, see the following Control members: CanFocus, CanSelect, Focused, ContainsFocus, Focus, Select.

Hint:

You maybe want to use the Controls property to access the child controls:

if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
    var child_TextBox = textBoxGroupName.Controls["myTextBox"]
    if(child_TextBox.CanFocus)
        child_TextBox.Focus(FocusState.Programmatic);
}

Upvotes: 2

Damir Arh
Damir Arh

Reputation: 17865

OnNavigatedTo happens to early in the page lifetime for setting the focus to work. You should call your code in the Loaded event:

private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
    {
        textBoxGroupName.Focus(FocusState.Programmatic);
    }
}

Of course you need to setup the handler in your .xaml file (I've omitted the other attributes in the Page element:

<Page
    Loaded="MainPage_OnLoaded">

Upvotes: 4

Related Questions