具有预定义模板的动态Tabitem

时间:2013-06-26 12:29:07

标签: wpf templates dynamic tabcontrol tabitem

我有一个动态创建标签的WPF应用程序,现在我希望每个标签项必须包含expandder和Usercontrol ,并且在运行时设置datandertext for Expander和Usercontrol ,所以如果我在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>

在codebehind ill中添加内容,

     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

现在我需要使用expandder和Usercontrol 模板化内容,我该如何实现?

1 个答案:

答案 0 :(得分:1)

您只需要向ContentTemplate添加TabControl(如果您愿意,还可以TabItem)。我会在XAML中完成所有工作:

<TabControl>
  <TabControl.ContentTemplate>
    <DataTemplate>
      <Expander>
        <my:UserControl />
      </Expander>
    </DataTemplate>
  </TabControl.ContentTemplate>
</TabControl>

由于这是一个模板,DataContext将是您设置为ThumbnailImages的内容的TabControl对象。

我要提到的另一件事是你可以设置HeaderTemplate的{​​{1}}属性,这样你就不必在代码中访问它。如果您要处理标题和/或内容的多个模板,请查看DataTemplateSelector