Search code examples
wpfxamlmenucentering

XAML Centering menuitem


So I made a simple menu with a Width of 55 I try to make my title ("FILE") centered within the button itself while still being on the left of the window.

At the moment the basic code looks like that

<Menu Height="25" VerticalAlignment="Top" Width="800" Margin="0">
<MenuItem Header="File" Margin="0" Height="25" Width="55" HorizontalContentAlignment="Center">
    <MenuItem Header="Login"/>
    <MenuItem Header="New User"/>
    ...
</MenuItem> </Menu>

I've already tried playing around with a code like

        <Menu.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid/>
            </ItemsPanelTemplate>
        </Menu.ItemsPanel>

To remove the grid but no sucess it's only the actual menu being centered and not the text "FILE" within the button.

Here's an example of what the "FILE" looks like at the moment and I try to make it centered within the blue area.

https://i.sstatic.net/KRXw2.png (Cannot post the actual image I don't have enough rep.)

Thanks.


Solution

  • You an achieve this by setting the MenuItem's header template to be a TextBlock, with the TextBlock being the same width of the MenuItem itself. Also, you will need to add a Margin to compensate for the default MenuItem template.

    <Menu Height="25" VerticalAlignment="Top" Width="800" Margin="0">
        <MenuItem Margin="0" Height="25" Width="55" HorizontalContentAlignment="Center">
            <MenuItem.Header>
                <TextBlock Text="File" HorizontalAlignment="Stretch" Margin="-7" Width="55" TextAlignment="Center"/>
            </MenuItem.Header>
            <MenuItem Header="Login"/>
            <MenuItem Header="New User"/>
        </MenuItem>
    </Menu>