Search code examples
wpfxaml

How I can align MenuItems in Menu to right?


In a menu bar, I want to get the two last buttons (here RUN and ADD) to the right instead of left

I tried to use HorizontalAlignment without success:

<Menu>
    <Menu.ItemsPanel>
        <ItemsPanelTemplate>
            <DockPanel HorizontalAlignment="Stretch"/>
        </ItemsPanelTemplate>
    </Menu.ItemsPanel>
    <MenuItem Header="FILE"/>
    <MenuItem Header="EDIT"/>
    <MenuItem Header="VIEW"/>
    <MenuItem Header="RUN" HorizontalAlignment="Right"/>
    <MenuItem Header="ADD" HorizontalAlignment="Right"/>
</Menu>

Solution

  • Your issue is in the

    <ItemsPanelTemplate>
        <DockPanel HorizontalAlignment="Stretch"/>
    </ItemsPanelTemplate>
    

    This is what describes the container your MenuItems will belong in. You need to use a panel here which allows you to horizontally align items to the right within it.

    You could try keeping it as a DockPanel:

    <DockPanel LastChildFill="False" HorizontalAlignment="Stretch"> 
    

    And adding

    DockPanel.Dock="Right"
    

    To the MenuItems you need to align right, and

    DockPanel.Dock="Left"
    

    To the others. If this does not work, there are plenty of other panels you can use in place of the DockPanel in the ItemsPanelTemplate.