I have a WPF app which creates tab dynamically,now I want the every tab item must contain expander and Usercontrol and also ill set the datacontext for Expander and Usercontrol during run time, so if i define the template for tabitem in Style,i feel it wuld be difficult for setting datacontext for expnder and usercontrol. In order for HeaderTemplate
XAML Code
<TabControl Name="tabDynamic" ItemsSource="{Binding}" SelectionChanged="tabDynamic_SelectionChanged" FontSize="15" FontFamily="Verdana" FontWeight="Normal" FontStretch="Expanded" >
<TabControl.Resources>
<DataTemplate x:Key="TabHeader" DataType="TabItem">
<DockPanel>
<Button Name="btnDelete" DockPanel.Dock="Right" Margin="150,0,0,0" Content="X" Foreground="WhiteSmoke" FontSize="10"
FontWeight="Bold" Padding="0" Click="btnDelete_Click" Height="15"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Name}" >
<Button.Background>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="#FF9D4040" Offset="0" />
<GradientStop Color="#FFB11212" Offset="1" />
</LinearGradientBrush>
</Button.Background>
<!--<Image Source="/delete.gif" Height="11" Width="11"></Image>-->
</Button>
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=TabItem }, Path=Header}" />
</DockPanel>
</DataTemplate>
</TabControl.Resources>
</TabControl>
In codebehind ill add the content,
Private Function AddTabItem() As TabItem
Dim count As Integer = _tabItems.Count
Dim tab As New TabItem()
tab.Header = String.Format("tab{0}", count)
tab.Name = String.Format("tab{0}", count)
tab.HeaderTemplate = TryCast(tabDynamic.FindResource("TabHeader"), DataTemplate)
_tabItems.Insert(count - 1, tab)
obj = New ThumbnailImages
' add controls to tab item,
If ImageCollection.Count > 0 Then
obj.SetDataContext(ImageCollection)
tab.Content = obj
End If
Return tab
End Function
Now i need the content to be templated with expander and Usercontrol, how can i achieve ?
You just need to add a ContentTemplate to the TabControl (or TabItem if you prefer). I would do it all in XAML:
<TabControl>
<TabControl.ContentTemplate>
<DataTemplate>
<Expander>
<my:UserControl />
</Expander>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
Because this is a template, the DataContext will be the ThumbnailImages object you're setting as the content to the TabControl.
Another thing I would mention is that you can set the HeaderTemplate property of the TabControl so you don't have to access it in code. And if you are dealing with multiple templates for the header and/or content, look into the DataTemplateSelector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With