我有一个动态创建选项卡的 WPF 应用程序,现在我希望每个选项卡项都必须包含扩展器和用户控件,并且在运行时也为扩展器和用户控件设置数据上下文,所以如果我在 Style 中定义 tabitem 的模板,我会感觉到为 expnder 和 usercontrol 设置 datacontext 会很困难。为了 HeaderTemplate
XAML 代码
<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>
在代码隐藏中添加内容,
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
现在我需要使用扩展器和 Usercontrol 模板化内容,我该如何实现?