Binding WPF menu items to WPF Tab Control Items collection
- by William
I have a WPF Menu and a Tab control. I would like the list of menu items to be generated from the collection of TabItems on my tab control. I am binding my tab control to a collection to generate the TabItems. I have a TabItem style that uses a ContentPresenter to display the TabItem text in a TextBlock. When I bind the tab items to my menu the menu items are blank. I assume the menu items are looking for the Header property of the TabItems which I am not using. Is there a workaround for my scenario? Is it possible to bind to the Header property of the tab item, when I do not know the number of tabs in advance? Below is a copy of my xaml declarations. Tab Control and items:
<DataTemplate x:Key="ClosableTabItemTemplate">
<DockPanel HorizontalAlignment="Stretch">
<Button
Command="{Binding Path=CloseWorkSpaceCommand}"
Content="X"
Cursor="Hand"
DockPanel.Dock="Right"
Focusable="False"
FontFamily="Courier"
FontSize="9"
FontWeight="Bold"
Margin="10,1,0,0"
Padding="0"
VerticalContentAlignment="Bottom"
Width="16" Height="16"
Background="Red"
/>
<ContentPresenter HorizontalAlignment="Center"
Content="{Binding Path=DisplayName}">
<ContentPresenter.Resources>
<Style TargetType="{x:Type TextBlock}"/>
</ContentPresenter.Resources>
</ContentPresenter>
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="WorkspacesTemplate">
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource ClosableTabItemTemplate}"
Margin="10"
Background="#4C4C4C"/>
</DataTemplate>
My Menu
<Menu Background="Transparent">
<MenuItem Style="{StaticResource TabMenuButtonStyle}"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TabControl}}, Path=Items}"
ItemContainerStyle="{StaticResource TabMenuItem}">
</MenuItem>
</Menu>