Dmitry Nogin
Dmitry Nogin

Reputation: 3750

Stretch-fill menu item header in WPF

How to stretch-fill menu item header content? I mean something like this:

<Menu>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <Ellipse Fill="Red" MinWidth="20" MinHeight="20"
        VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
    <Ellipse Fill="Green" MinWidth="20" MinHeight="20" 
        VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
</Menu>

Ellipses are just 20x20...

Upvotes: 1

Views: 2287

Answers (1)

Sphinxxx
Sphinxxx

Reputation: 13057

The menu puts each Ellipse inside a MenuItem, and the default MenuItem template doesn't allow its content to stretch. Therefore, you need to override that template, via ItemContainerStyle:

<Menu>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <!-- New MenuItem template: -->
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="MenuItem">
                        <Border Background="Gold" BorderBrush="Black" BorderThickness="2" Margin="1" >
                            <ContentControl Content="{TemplateBinding Header}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ItemsControl.ItemContainerStyle>

    <Ellipse Fill="Red" MinWidth="20" MinHeight="20"
             VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
    <Ellipse Fill="Green" MinWidth="20" MinHeight="20" 
             VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
</Menu>

Upvotes: 2

Related Questions