我在 Blend
中添加了一个 Pivot Control
和三个 PivotItems
。每个PivotItem
都有一个ViewModel
,因为它是DataContext
。每个ViewModel
都有一个字符串属性Title
。我想编辑 Header Template
,创建一个 TextBlock
并将其 Text
属性绑定(bind)到 Title
,但对于某些原因是它不起作用。我确定这是因为 Header Template
的 DataContext
为空,但我认为它会从特定的 PivotItem
继承。这是 header 模板的 xaml
代码。
<DataTemplate x:Key="HeaderTemplate">
<Grid Height="47" Width="354">
<TextBlock Margin="8,0,64,8" TextWrapping="Wrap" Text="{Binding Title}" d:LayoutOverrides="Width" FontSize="24" Foreground="Red"/>
</Grid>
</DataTemplate>
<controls:Pivot TitleTemplate="{StaticResource TitleTemplate}" HeaderTemplate="{StaticResource HeaderTemplate}">
<!--Pivot item one-->
<controls:PivotItem DataContext="{Binding Home, Mode=OneWay}">
<Grid>
<ListBox x:Name="listBox" ItemsPanel="{StaticResource HomeItemsPanel}" ItemTemplate="{StaticResource HomeItemTemplate}" ItemsSource="{Binding Tiles}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding OnSelectionChanged}" CommandParameter="{Binding SelectedIndex, ElementName=listBox}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
</Grid>
</controls:PivotItem>
<controls:PivotItem Margin="0,8,0,1">
<Grid/>
</controls:PivotItem>
<!--Pivot item two-->
<controls:PivotItem DataContext="{Binding More, Mode=OneWay}">
<Grid/>
</controls:PivotItem>
</controls:Pivot>
我想创建一个更复杂的标题模板
,但现在我正在测试是否可以绑定(bind)它,然后再继续处理不仅仅是 TextBlock 的内容。我知道我可以将 ViewModels
的 List
用于 PivotControl.ItemSource
,但随后我必须使用 DataTemplateSelector
等等,我不想要这样。
所以我想我的问题是这样的,如何使 HeaderTemplate 继承相应 PivotItem
的 DataContext?
谢谢。
最佳答案
那是行不通的。您应该按以下方式编写 HeaderTemplate:
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</controls:Pivot.HeaderTemplate>
Textblock 将从 PivotItem 的 Header 属性接收绑定(bind)。对于每个 PivotItem,您绑定(bind)其标题:
<controls:PivotItem Header="{Binding Title}">
<Grid/>
</controls:PivotItem>
唯一的问题仍然是将每个数据透视项绑定(bind)到其自己的数据上下文。您可以使用以下代码手动为每个项目执行此操作:
<controls:PivotItem DataContext="{Binding Item1}" Header="{Binding Title}">
<Grid/>
</controls:PivotItem>
<controls:PivotItem DataContext="{Binding Item2}" Header="{Binding Title}">
<Grid/>
</controls:PivotItem>
关于data-binding - 绑定(bind)数据透视 header 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480393/