2

我希望 MenuItem 的高度为 24,就像菜单一样。目前它有 18 个。我可以将 Height="24" 添加到 MenuItem 但我不想这样做,如果我这样做,那么文本将不会垂直居中。为什么我的 VerticalAlignment 和 VerticalContentAlignment 没有被拾起?样式的其他属性被拾取,所以我知道样式被应用了。

<Grid Background="Orange">
    <Grid.RowDefinitions>
        <RowDefinition Height="24"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Menu Grid.Row="0">
        <MenuItem Header="Project" />
    </Menu>
    <Grid Grid.Row="1">
        <Border BorderBrush="Orange" BorderThickness="2" Margin="2" CornerRadius="8,8,8,8">
        </Border>
    </Grid>
</Grid>

    <Style TargetType="MenuItem">
        <Setter Property="VerticalAlignment" Value="Stretch" />
        <Setter Property="VerticalContentAlignment" Value="Center" />
    </Style>

编辑我尝试了“nit”的解决方案并将其移至如下样式:

<Style TargetType="MenuItem">
        <Setter Property="FontSize" Value="11" />
        <Setter Property="FontFamily" Value="Verdana" />
        <Setter Property="Padding" Value="0" />
        <Setter Property="Margin" Value="5,0,10,0" />
        <!-- variation on 'nit''s proposal -->
        <Setter Property="Height" Value="{Binding RelativeSource={RelativeSource Self}, Path=Parent.ActualHeight}"/>
        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate>
                    <!-- variation on 'nit''s proposal -->
                    <TextBlock VerticalAlignment="Center" Text="{Binding RelativeSource={RelativeSource AncestorType=MenuItem}, Path=Header}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

它似乎在一个窗口中工作,例如

<Menu Grid.Row="0" Name="MainMenu" Height="24">
   <MenuItem Header="Project">
       <MenuItem Header="Open... Ctrl+O">
           <MenuItem.Icon>
              <Image Width="20" Height="20" Source="/Resources/openfile.jpg" />
           </MenuItem.Icon>
        </MenuItem> </MenuItem> ...etcetera

仅将 DataTemplate 用于外观感觉有点奇怪,但 ControlTemplate 破坏了内置的 MenuItem 功能。这是处理问题的正确方法吗?

4

1 回答 1

2

This is how you can align your menuitems :

       <Menu   Grid.Row="0">
            <MenuItem  Height="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType={x:Type Menu}}}" Header="Project" >
                <MenuItem.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock VerticalAlignment="Center" Text="{Binding Header, RelativeSource={RelativeSource x:AncestorType=MenuItem}}"/>
                    </DataTemplate>
                </MenuItem.HeaderTemplate>
            </MenuItem>
        </Menu>

you can move this headertemplate and height binding in your menuitem style

于 2013-09-27T16:20:51.440 回答