Search code examples
c#wpfwindows

WPF Right-Aligning Menu Item Moves Menu to Centre of Window


I'm trying to right-align a single menu item though a method found here, but applying this method (seen in the code below) moves the menu to the center of the window, and I can't find an elegant solution to move it back to the top.

<DockPanel>
            <Menu>
                <Menu.ItemsPanel>
                    <ItemsPanelTemplate>
                        <DockPanel/>
                    </ItemsPanelTemplate>
                </Menu.ItemsPanel>
                <MenuItem Header="File">
                    <MenuItem Header="Home" Click="MenuItem_Home_Click"/>
                    <MenuItem Header="About"/>
                    <MenuItem Header="Settings" Click="MenuItem_Settings_Click"/>
                    <Separator/>
                    <MenuItem Header="Exit" Click="MenuItem_Exit_Click"/>
                </MenuItem>
                <MenuItem Header="Notifications" HorizontalAlignment="Right" FlowDirection="RightToLeft"/>
            </Menu>
</DockPanel>

Menu location with code

Don't suppose anyone can work out what I've done wrong here?

I've tried various different methods to fix this, only removing the whole Menu.ItemsPanel code works in returning the menu to it's original location, but that also moves the Notifications menu item to the left.


Solution

  • You need to put it in a container, such as a grid, that restricts it's height.

    
    <Grid>
    
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
    
      <Menu Grid.Row="0">
        <Menu.ItemsPanel>
            <ItemsPanelTemplate>
                <DockPanel HorizontalAlignment="Stretch"/>
            </ItemsPanelTemplate>
        </Menu.ItemsPanel>
        <MenuItem Header="File">
            <MenuItem Header="Home" Click="MenuItem_Home_Click"/>
            <MenuItem Header="About"/>
            <MenuItem Header="Settings" Click="MenuItem_Settings_Click"/>
            <Separator/>
            <MenuItem Header="Exit" Click="MenuItem_Exit_Click"/>
        </MenuItem>
        <MenuItem Header="Notifications" HorizontalAlignment="Right" FlowDirection="RightToLeft"/>
      </Menu>
    </Grid>