【发布时间】:2020-10-12 12:15:48
【问题描述】:
对于 UWP Pivot,我如何有问题地选择特定的 PivotItem(选项卡)?
这是我目前所拥有的。请注意,在 ViewModel 的 Load 方法中,我尝试设置 SelectedIndex。这只是抛出一个异常,那么如何使 PivotItem 成为代码中的活动项呢?
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);
}
}
【问题讨论】: