eoweww eoweww - 2 months ago 9
C# Question

Menu does not stick on top WPF C#

Just look at images you will understand

When I starts program first view=>Click
enter image description here

When maximize its form its view=>Click
enter image description here

I am very new to WPF and I don't know how to fix this problem this is my code:

<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">

<Grid>
<Menu Margin="0,0,0,285">
<MenuItem Header="File" Name="meFile"></MenuItem>
<MenuItem Header="Edit" Name="meEdit"></MenuItem>
<MenuItem Header="View" Name="meView"></MenuItem>
<MenuItem Header="Project" Name="meProject"></MenuItem>
<MenuItem Header="Build" Name="meBuild"></MenuItem>
<MenuItem Header="Debug" Name="meDebug"></MenuItem>
<MenuItem Header="Team" Name="meTeam"></MenuItem>
</Menu>
</Grid>


</Window>

Answer
  1. Remove Margin altogether and use VerticalAlignment="Top" to make it work with Grid.

  2. Don't use Grid, DockPanel is the way to go. Eg;

    <DockPanel LastChildFill="False">
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File" Name="meFile"></MenuItem>
            <MenuItem Header="Edit" Name="meEdit"></MenuItem>
            <MenuItem Header="View" Name="meView"></MenuItem>
            <MenuItem Header="Project" Name="meProject"></MenuItem>
            <MenuItem Header="Build" Name="meBuild"></MenuItem>
            <MenuItem Header="Debug" Name="meDebug"></MenuItem>
            <MenuItem Header="Team" Name="meTeam"></MenuItem>
        </Menu>
    </DockPanel>
    

You might need to set Height if you won't set LastChildFill = False.