0

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.

yoduh
  • 7,074
  • 2
  • 11
  • 21

1 Answers1

0

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>
Tarazed
  • 1,707
  • 1
  • 7
  • 22
  • This also places the menu in the centre of the window unfortunately – Atlas Tabula Dec 14 '22 at 18:39
  • @AtlasTabula I apologize I missed where you said it was centering vertically. I was thinking it was centering horizontally. I've updated my answer. – Tarazed Dec 14 '22 at 19:07
  • Ah, works perfectly now, thank you. Didn't even realise you could apply grid rows to menus – Atlas Tabula Dec 14 '22 at 19:55
  • @AtlasTabula That is called an [Attached Property](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/properties/attached-properties-overview). Any child element of Grid can specify it's Row and Column. – Tarazed Dec 14 '22 at 20:24