Tuesday, September 17, 2013

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

Inline image 2

To bind a TabControl to a list of objects, you can set the ItemSource 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>

QR: Inline image 1