Search code examples
uwpuwp-xaml

UWP - set active PivotItem from view model


For a UWP Pivot, how do I problematically select a particular PivotItem (tab)?

Here is what I have so far. Notice in the ViewModel's Load method I attempt to set the SelectedIndex. This just throws an exception, so how do make a PivotItem the active one from code?

MainPage.xaml

<StackPanel>
    <Pivot x:Name="pivot" SelectedItem="{x:Bind ViewModel.PivotSelectedIndex, Mode=TwoWay}">
        <PivotItem Header="A">
            <TextBlock Text="Tab A Content" />
        </PivotItem>
        <PivotItem Header="B">
            <TextBlock Text="Tab B Content" />
        </PivotItem>
        <PivotItem Header="C">
            <TextBlock Text="Tab C Content" />
        </PivotItem>
        <PivotItem Header="D">
            <TextBlock Text="Tab D Content" />
        </PivotItem>
        <PivotItem Header="E">
            <TextBlock Text="Tab E Content" />
        </PivotItem>
    </Pivot>
</StackPanel>

MainPage.xaml.cs

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        ViewModel = new MainPageViewModel();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        ViewModel.Load();
    }

    public MainPageViewModel ViewModel
    {
        get { return (MainPageViewModel)GetValue(ViewModelProperty); }
        set { SetValue(ViewModelProperty, value); }
    }
    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(MainPageViewModel), typeof(MainPage), new PropertyMetadata(null));
}

MainPageModel.cs

public class MainPageViewModel : ObservableObject
{
    public void Load()
    {
        PivotSelectedIndex = 2;
    }

    private int _pivotSelectedIndex = 0;
    public int PivotSelectedIndex
    {
        get => _pivotSelectedIndex;
        set => Set(ref _pivotSelectedIndex, value);
    }
}

Solution

  • Use SelectedIndex instead of SelectedItem:

    <Pivot x:Name="pivot" SelectedIndex="{x:Bind ViewModel.PivotSelectedIndex, Mode=TwoWay}">