Reputation: 2898
I have a Pivot Control
and three PivotItems
added in Blend
. Each PivotItem
has a ViewModel
as it's DataContext
. Each ViewModel
has a string property Title
. I want to edit the Header Template
, create a TextBlock
and bind it's Text
property to Title
, but for some reason it doesn't work. I am sure it's because the DataContext
of the Header Template
is null, but I thought it would be inherited from the specific PivotItem
. This is the xaml
code for the Header Template.
<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>
I want to create a more complex Header Template
but for now I am testing if I can bind it, before proceeding on with something more than just a TextBlock. I know that I could use a List
of ViewModels
for the PivotControl.ItemSource
, but then I would have to use a DataTemplateSelector
and so on, and I don't want that.
So I guess my question is this, how can I make the HeaderTemplate inherit the DataContext of the according PivotItem
?
Thank you.
Upvotes: 2
Views: 1762
Reputation: 7112
That won't work. You should write HeaderTemplate the following way:
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</controls:Pivot.HeaderTemplate>
Textblock will receive the binding from the PivotItem's Header property. For each PivotItem, you bind its Header:
<controls:PivotItem Header="{Binding Title}">
<Grid/>
</controls:PivotItem>
The only problem remains in binding each pivot item to its own data context. You can do that manually for each item with the following code:
<controls:PivotItem DataContext="{Binding Item1}" Header="{Binding Title}">
<Grid/>
</controls:PivotItem>
<controls:PivotItem DataContext="{Binding Item2}" Header="{Binding Title}">
<Grid/>
</controls:PivotItem>
Upvotes: 2