Home > Back-end >  How do I attach a label to the menu in WPF?
How do I attach a label to the menu in WPF?

Time:03-11

I want to attach Label to the Menu, where I have components of MenuItem. I need to hide some MenuItems (I use Visibility.Collapsed). When I do it, labels move. How to fit it?

The first condition of Menu.

The second condition of Menu.

<Menu x:Name="Menu" DockPanel.Dock="Top">
    <MenuItem Name="MenuStartGame" Header="Start new game" FontSize="16" Click="MenuStartGame_Click">
    </MenuItem>
    <MenuItem Name="MenuCancelMyTurn" Header="Cancel my turn" FontSize="16" Visibility="Collapsed" Click="CancelMyTurn_Click">
    </MenuItem>
    <MenuItem Name="MenuAddButtons" Header="Add buttons" FontSize="16" Click="AddButtons_Click">
    </MenuItem>
    <MenuItem Name="MenuRemoveButtons" Header="Remove buttons" FontSize="16" Click="RemoveButtons_Click">
    </MenuItem>
    <Label x:Name="labelTime" HorizontalContentAlignment="Center" Content="" Width="100">
    </Label>
    <Label x:Name="labelScore" HorizontalContentAlignment="Center" Content="" Width="100">
    </Label>
</Menu>

CodePudding user response:

If you do not want labels to move when you hide or show the others, you should not use Visibility.Collapsed, use Visibility.Hidden.

Maybe, if I understand correctly what you want to do, a Menu is not what you should use in your case. You can use a Grid and have a greater control on what the dimensions of your columns will be. Something like this:

<Grid x:Name="Menu" DockPanel.Dock="Top">
 <Grid.ColumnDefinitions>
   <ColumnDefinition Width="Auto" />
   <ColumnDefinition Width="*" />
   <ColumnDefinition Width="Auto" />
   <ColumnDefinition Width="Auto" />
 </Grid.ColumnDefinitions>
    <Button Grid.Column="0" Name="MenuStartGame" Header="Start new game" FontSize="16" Click="MenuStartGame_Click">
    </Button>
    <ButtonName="MenuCancelMyTurn" Grid.Column="1" Header="Cancel my turn" FontSize="16" Visibility="Collapsed" Click="CancelMyTurn_Click">
    </Button>
    <DockPanel Grid.Column="1">
     <ButtonName="MenuAddButtons" Header="Add buttons" FontSize="16" Click="AddButtons_Click">
     </Button>
     <ButtonName="MenuRemoveButtons" Header="Remove buttons" FontSize="16" Click="RemoveButtons_Click">
     </Button>
    </DockPanel>
    <Label Grid.Column="2" x:Name="labelTime" HorizontalContentAlignment="Center" Content="" Width="100">
    </Label>
    <Label Grid.Column="3" x:Name="labelScore" HorizontalContentAlignment="Center" Content="" Width="100">
    </Label>
</Grid>

This is not tested, but should be what you need.

  • Related