TabItem in a separate XAML

If what you want to do is simply make the code more manageable then I would recommend defining each tab’s data in a user control, but still have the TabItem in the main tab control.

Let’s assume that your original code was this:

<TabControl>
    <TabItem Header="Tab 1">
        <Grid>
            <TextBlock Text="Tab Data" />
        </Grid>
    </TabItem>
</TabControl>

To make the code more manageable you could break the tab contents into a UserControl such as:

<UserControl x:Class="WpfApplication19.Tab1Data"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             >
    <Grid>
        <TextBlock Text="Tab Data" />
    </Grid>
</UserControl>

And then use that user control in your TabControl like this:

    <TabControl>
        <TabItem Header="Tab 1">
            <tabData:Tab1Data />
        </TabItem>
    </TabControl>

If you really want to include the TabItem in your user control then you can do that by first creating a user control, and then change the type of the user control to the type TabItem (make sure you change this in both the xaml root node and the code behind).

This would leave you with a tab control that looks like this:

    <TabControl>
        <tabData:TabItem1 />
        <tabData:TabItem2 />
        <tabData:TabItem3 />
    </TabControl>

And each TabItem1 ‘User Control’ would be of type TabItem. Here is an example:

<TabItem x:Class="WpfApplication19.TabItem1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Header="Tab 1"
         >
    <Grid>
        <TextBlock Text="Tab Data" />
    </Grid>
</TabItem>

And as I mentioned, be sure to change the code behind so that it extends TabItem instead of user control:

public partial class TabItem1 : TabItem
{
    public TabItem1()
    {
        InitializeComponent();
    }
}

Leave a Comment