Phil Wright
Phil Wright

Reputation: 22956

UWP Pivot control, how to set focus to first control within PivotItem

I have a Pivot control that uses an ItemsSource to bind to a list of ViewModel instances. I assign a custom ItemTemplateSelector to map between ViewModel types and DataTemplate definitions. This all works fine and the correct display is created for each ViewModel based on the associated DataTemplate. Something like this...

<Pivot ItemsSource="{x:Bind ViewModels}"
       ItemTemplateSelector="{StaticResource ViewModelSelector}"
       SelectedItem="{x:Bind SelectedViewModel, Mode=TwoWay}"/>

The problem is that I want to automatically set focus to a control within each page when that page is first shown. They are typically data entry forms and so the user currently has to select the first control to start entering data. It would be better if first showing a page automatically then set focus to a control on that page.

Any ideas?

Upvotes: 0

Views: 266

Answers (1)

Bite
Bite

Reputation: 302

You could bind a method to the TextBox when it's loaded.

For example:

<Pivot.ItemTemplate>
            <DataTemplate x:DataType="local:Test">
                <TextBox Text="{x:Bind Content}" Height="50" Loaded="{x:Bind TextBox_Loaded}">
                </TextBox>
            </DataTemplate>
        </Pivot.ItemTemplate>
public void TextBox_Loaded(object sender, RoutedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        if (textBox != null)
        {
            textBox.Focus(FocusState.Programmatic);
        }
    }

Upvotes: 0

Related Questions