我将 PivotItems 与 MVVM 绑定,然后尝试更改标题的前景色。问题是当我仅以编程方式添加项目时我的代码有效。现在有了这个绑定,我的标题是我的自定义对象,我不能正确地转换它:
private void Pivot_SelectionChanged(object sender, Windows.UI.Xaml.Controls.SelectionChangedEventArgs e)
{
if (0 < e.AddedItems.Count)
{
PivotItem currentItem = e.AddedItems[0] as PivotItem;
if (null != currentItem)
{
if (null != currentItem.Header)
{
(currentItem.Header as TextBlock).Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
}
}
}
if (0 < e.RemovedItems.Count)
{
PivotItem currentItem = e.RemovedItems[0] as PivotItem;
if (null != currentItem)
{
if (null != currentItem.Header)
{
(currentItem.Header as TextBlock).Foreground = new SolidColorBrush(Color.FromArgb(64, 255, 255, 255));
}
}
}
}
此行会导致问题,因为现在 e.AddedItems[0] 不是 PivotItem 类型,而是我的自定义对象,因此它为 null..
PivotItem currentItem = e.AddedItems[0] as PivotItem;
这是我的 XAML:
<Pivot x:Name="MyPivot" Title="MasterViewModel" Foreground="#FF888888" Style="{StaticResource PivotStyle1}" SelectionChanged="Pivot_SelectionChanged" Margin="0" Grid.Row="1" ItemsSource="{Binding MyCustomViewModel.Se}" ItemTemplate="{StaticResource MyTemplate1}">
<Pivot.HeaderTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding myProp}" Margin="0, 16, 0, 0" Foreground="#FF888888" FontSize="32" FontFamily="Segoe WP" FontWeight="Light"/>
</Grid>
</DataTemplate>
</Pivot.HeaderTemplate>
</Pivot>