c# - 将菜单标题居中 wpf

标签 c# wpf xaml

我有一个包含菜单的 WPF 应用程序。我需要将菜单标题居中:

 <MenuItem Header="_Paramètres" Height="60" Width="188" FontWeight="Bold" FontSize="16" HorizontalContentAlignment="Center"  >
     <MenuItem Header="_Régler" Height="30" Width="188" FontWeight="Bold" FontSize="16" Click="regler_Click_1"  x:Name="regler" Background="#FF150202" HorizontalContentAlignment="Center" />
 </MenuItem>

菜单项居中但菜单标题不居中。

我该怎么做?

最佳答案

您应该另外设置根MenuItemHorizo​​ntalAlignment。像这样。

<MenuItem Header="_Paramètres" Height="60" Width="188" FontWeight="Bold" FontSize="16" 
          HorizontalContentAlignment="Center" HorizontalAlignment="Center" >
    <MenuItem Header="_Régler" Height="30" Width="188" FontWeight="Bold" FontSize="16" 
              Click="regler_Click_1"  x:Name="regler" Background="#FF150202"/>
</MenuItem>

此代码不需要设置子 MenuItemsHorizo​​ntalAlignment

您可以找到有关 HorizontalAlignment 的一些附加信息和 HorizontalContentAlignment在链接中。

编辑

好的(评论中的问答),那么以下内容可能会有所帮助。

<MenuItem Header="_Paramètres" Height="60" Width="188" FontWeight="Bold" FontSize="16" 
          HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" >
    <MenuItem Header="_Régler" Height="30" Width="188" FontWeight="Bold" FontSize="16" 
              Click="regler_Click_1"  x:Name="regler" Background="#FF150202"
              HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"/>
</MenuItem>

顺便说一句,您应该创建一个Style,以便您可以重复使用这些设置。

编辑2

最后的想法。如果这不起作用,我将永远不会再次使用 XAML 实现 UI。 ;o)

<!-- Declare this as resource -->
<Style x:Key="CenteredTextMenuItem" x:TargetType="MenuItem">
    <Setter Property="HeaderTemplate">
        <DataTemplate>
            <TextBox Text={Binding} HorizontalAlignment="Stretch" 
                     HorizontalContentAlignment="Center" FontSize="16" FontWeight="Bold"/>
        </DataTemplate>
    </Setter>
    <Setter Property="Height" Value="30"/>
    <Setter Property="Width" Value="188"/>
</Style>

用法

<MenuItem Header="_Paramètres" Height="60" Style="{StaticResource CenteredTextMenuItem}" >
    <MenuItem x:Name="regler" Header="_Régler" Click="regler_Click_1"  
              Background="#FF150202" Style="{StaticResource CenteredTextMenuItem}"/>
</MenuItem>

关于c# - 将菜单标题居中 wpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15950058/

相关文章:

c# - 在 C# 线程中传递参数化方法时出错

WPF 数据网格标题文本绑定(bind)

c# - MVVM+ WPF PopUp 打不开

wpf - 组合框显示成员路径上的 StringFormat

c# - WPF:命名空间中不存在该名称

c# - DynamicObject 对于空值的行为不同

c# - 延迟域事件的创建和调度

c# - 我们可以将数据表从业务层传递到表示层吗?

c# - 为用户无法选择的上下文菜单添加标题

wpf - WPF 中的上下文菜单继承