2
votes

I want the MenuItem to have a height of 24, like the menu. Currently it has 18. I can add Height="24" to the MenuItem but I don't want to do that, and if I do, then the text won't center vertically. Why are my VerticalAlignment and VerticalContentAlignment not picked up? Other properties of the style are picked up, so I know that the style is applied.

<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>

EDIT I tried the solution of 'nit' and moved it to a style like this:

<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>

It seems to work in a window with e.g.

<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

It feels a bit strange to use a DataTemplate for appearance only, but a ControlTemplate breaks the built-in MenuItem functionality. Is this a correct way to handle the issue?

1

1 Answers

2
votes

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