在菜单控件中居中MenuItem的内容

时间:2016-07-27 13:50:11

标签: wpf xaml menu menuitem

我有一个非常愚蠢的问题,我无法解决。 对于我的项目,我使用WPF(和MVVM),并希望看起来很漂亮的垂直对齐Menu控件。 但我无法将MenuItems的内容集中在一起。

以下是我的菜单的XAML代码:

<Menu ItemsSource="{Binding Commands}" 
      ItemTemplate="{StaticResource CommandsTemplate}" 
      ItemContainerStyle="{StaticResource CommandsStyle}">
    <Menu.ItemsPanel>
        <ItemsPanelTemplate>
             <VirtualizingStackPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </Menu.ItemsPanel>
</Menu>

这是我的模板和我的风格:

<DataTemplate x:Key="CommandsTemplate">
    <StackPanel Margin="4">
        <Image Source="{Binding IconSource}"/>
        <TextBlock Text="{Binding Path=DisplayName}" />
    </StackPanel>
</DataTemplate>

<Style x:Key="CommandsStyle" TargetType="MenuItem">
    <Setter Property="Command" Value="{Binding Command}"/>
    <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
</Style>

我尝试将HorizontalAlignment的{​​{1}} StackPanel CenterHorizontalContentAlignment Menu设置为Center等等。似乎没有任何效果。如果我设置StackPanel的背景颜色,我发现它的大小足以包裹我的图像和文字。如果我将鼠标悬停在某个项目上,则表示该菜单的全部宽度。在线我无法找到适用于我的情况的东西。

修改

以下是一个例子:

我希望整个事情都在菜单的中心,而不是图标旁边的文字!

编辑2

我测试了一些东西,接近我想要的东西。我将此添加到CommandsStyle

<Setter Property="HorizontalAlignment" Value="Center"/>

可悲的是,它在按钮上徘徊非常难看。

在:

后:

所以它仍然不是我想要的。

ANSWER

我几乎放弃了,并试图研究我MenuItem的其他设计事物。其中一个是改变它的悬停颜色。我发现了this帖子。然后我将HorizontalAlignment="Center"添加到我的StackPanel,现在就可以了!

以下是更新后的代码:

<Style x:Key="CommandsStyle" TargetType="MenuItem">
    <Setter Property="Command" Value="{Binding Command}"/>
    <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type MenuItem}">
                <Border x:Name="Bd"  BorderBrush="{TemplateBinding BorderBrush}" 
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}" 
                        SnapsToDevicePixels="True" 
                        Uid="Border_38">
                    <StackPanel HorizontalAlignment="Center" Margin="4">
                        <Image Width="32" Source="{Binding IconSource}"/>
                        <TextBlock Text="{Binding Path=DisplayName}" />
                    </StackPanel>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsHighlighted" Value="True">
                        <Setter Property="Background" TargetName="Bd" Value="LightGray"/>
                        <Setter Property="BorderBrush" TargetName="Bd" Value="Gray"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

当我将鼠标悬停在我的MenuItem上时,这就是它的样子:

0 个答案:

没有答案