Elmo
Elmo

Reputation: 6471

Same Content for all TabItems in TabControl

I want to show the same content for all TabItems in a TabControl:

<TabControl>
    <TabItem Header="Tab 1">
        <StackPanel>
            <ComboBox />
            <Button Content="Button" x:Name="bButton" />
        </StackPanel>
    </TabItem>
    <TabItem Header="Tab 2" />
    <TabItem Header="Tab 3" />
</TabControl>

Is there an easy way to do this without repeating the code and only in XAML (not using code-behind)?

Upvotes: 2

Views: 2477

Answers (3)

Elmo
Elmo

Reputation: 6471

I moved the <StackPanel> outside the <TabControl> and set the margins to place it on top of the TabControl:

<TabControl HorizontalAlignment="Left">
    <TabItem Header="Tab 1" />
    <TabItem Header="Tab 2" />
    <TabItem Header="Tab 3" />
</TabControl>
<StackPanel HorizontalAlignment="Left" Margin="5,50,0,0">
    <ComboBox />
    <Button Content="Button" x:Name="bButton" />
</StackPanel>

This is the cleanest and simplest approach.

Upvotes: -2

D J
D J

Reputation: 7028

you can do it like this. Define the common resource in xaml.

<Window.Resources>
    <StackPanel x:Key="CommonTabContent">
        <ComboBox />
        <Button Content="Button" x:Name="bButton" Click="bButton_Click_1" />
    </StackPanel>

</Window.Resources>

and use it like

<TabControl>
    <TabItem Header="Tab 1" Content="{StaticResource CommonTabContent}"/>
    <TabItem Header="Tab 2" Content="{StaticResource CommonTabContent}" />
    <TabItem Header="Tab 3" Content="{StaticResource CommonTabContent}" />
</TabControl>

Your .cs file code will contain the method.

private void bButton_Click_1(object sender, RoutedEventArgs e)
{
    // your code
}

hope it helps..

Upvotes: 3

Drew Noakes
Drew Noakes

Reputation: 310802

You could:

  1. Extract the content into a UserControl and use it in each TabItem
  2. Create a ControlTemplate and apply it to an instance of Control in each TabItem
  3. Define a DataTemplate and use the ItemsSource of TabControl to apply the template to each child

The first approach is probably the sanest, especially if you need to access the contents of each tab page separately.

Upvotes: 2

Related Questions