我希望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功能。这是处理问题的正确方法吗?
答案 0 :(得分:2)
这是您对齐菜单项的方法:
<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>
你可以在你的menuitem风格中移动这个headertemplate和高度绑定