TabControl.ItemTemplate: set TabItem.Header.Text to a MultiBinding with StringFormat

杀马特。学长 韩版系。学妹 提交于 2019-11-30 08:04:31

The TabControl contains a ContentTemplate property as well as the ItemTemplate that it inherits from ItemsControl. It uses the ContentTemplate to differentiate what is showing in the Content area while the ItemTemplate which defines the template for the Header. Additionally, each Item from your ItemSource will automatically be wrapped in a TabItem; it doesn't need to be re-created in the ItemTemplate, as that will attempt to place a TabItem inside the Header as you are noticing.

Instead of re-creating a TabItem inside the ItemTemplate, use the ItemTemplate to define your Header content, and the ContentTemplate to define your Content.

<TabControl ItemsSource="{Binding}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0}--{1}">
                        <Binding Path="Title" />
                        <Binding Path="Category.Title" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding MyContent}" />
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

In your first paragraph you mentioned wanting to set different sizes on the bound portions of the Header. If you do want to do that, you won't be able to use a single Binding or MultiBinding to set the Text as is done above. Instead you can nest TextBlocks to achieve this with different formatting for each.

<TabControl.ItemTemplate>
    <DataTemplate>
        <TextBlock>
            <TextBlock Text="{Binding Title}"
                       FontSize="12" />
            <Run Text="--" />
            <TextBlock Text="{Binding Category.Title}"
                       FontSize="10" />
        </TextBlock>
    </DataTemplate>
</TabControl.ItemTemplate>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!