#908 – Binding a TabControl to a List of Objects, part II

To bind a TabControl to a list of objects, you can set the ItemsSource of the TabControl to an ObservableCollection of the desired object type.  This will cause a new TabItem to be created for each element in the collection.

By default, both the header and the content of each TabItem is set to the result of invoking ToString on each item in the collection.  To set the Header of each tab, dictating what appears on the tab itself, you can set the ItemContainerStyle of the TabControl to a style element, where you set the HeaderTemplate, as shown below.

<TabControl Margin="5"
            ItemsSource="{Binding RomanDudes}">
    <TabControl.ItemContainerStyle>
        <Style TargetType="TabItem">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel>
                            <Image Source="{Binding Image}" Height="50"/>
                            <TextBlock Text="{Binding Name}" HorizontalAlignment="Center"/>
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.ItemContainerStyle>
</TabControl>

In the next post, we’ll set the content of each TabItem as well.
908-001

 

Note: For a cleaner way to do this, see: Use ItemTemplate to Control Content on Tabs