WPF中的拉伸填充菜单项标题

时间:2016-12-21 03:29:40

标签: c# wpf xaml

如何拉伸填充菜单项标题内容?我的意思是这样的:

<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只有20x20 ......

1 个答案:

答案 0 :(得分:2)

菜单会将每个Ellipse放在MenuItem内,默认MenuItem模板不允许其内容展开。因此,您需要通过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>