TabControl's TabItems sharing same content... Do Not Want

gotopie picture gotopie · Aug 15, 2010 · Viewed 8.5k times · Source

The following example xaml causes each tab item to share the same TextBox. It makes sense, on some level I guess... but it's unexpected behavior, and almost feels like a bug. And I couldn't find any information in the docs explaining the behavior, or how to correctly get around it.

<TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBox />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>
    <TabItem Name="tab1" />
    <TabItem Name="tab2" />
</TabControl>

When switching between tab1 and tab2, the same TextBox is used, when I would expect a new TextBox for each tab. How can I get the latter case?

Subclassing TabItem and making its content a TextBox by default is one way to do it, but I just want to be sure there isn't something I'm missing.

Edit

I realize that setting the content explicitly for each tab will solve the problem, but the tabs are to be created dynamically. I want to use the content template so that I may add new tabs via data binding and have the content unshared as it is causing quirky behavior.

Perhaps with the current implementation of the TabControl, there is no declarative approach to solving this. It's pretty trivial setting the content in code, but such things always feel wrong in WPF. To me, this seems like an unjustified optimization of the TabControl; it should at least be optional for situations where it is not practical.

Answer

Kent Boogaart picture Kent Boogaart · Aug 15, 2010

I suspect there's a nicer way to achieve whatever it is you're trying to achieve, but I think this will work (would test but I'm on linux atm):

<TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem" x:Shared="False">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBox />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>
    <TabItem Name="tab1" />
    <TabItem Name="tab2" />
</TabControl>