VerticalAlignment = "Stretch" for inner labeling does not work

How to use VerticalAlignment="Stretch" with a Label inside a Canvas ? I am trying to center the Cancel text in a button, as in the code below. Using a fixed height and width for the mark is not a desired option.

 <Button Name="buttonCancel" Width="80" Height="40" IsCancel="True" Padding="0" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"> <Canvas> <Label Canvas.Top="0" Canvas.Left="0" Padding="0" FontSize="10">Esc</Label> <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">Cancel</Label> </Canvas> </Button> 
+4
source share
4 answers

Use binding to Canvas ActualWidth :

 <Canvas> <Label Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Canvas}}, Path=ActualWidth}">...</Label> </Canvas> 

But, as mentioned above, if you are interested in dynamic stretch layouts, Canvas not an ideal control choice.

+6
source

A Canvas does not scale its content; if you want to scale the content, you can use the Grid in this case, which by default will scale both Label elements to fill the Content gap.

+1
source

Assuming you need a canvas for other objects that are fixed in nature, you can overlay the Canvas on the Grid and then place the labels in the grid. You can place labels in front of the canvas to make them a z-index background (overwritten canvas objects) or after the canvas to make them higher z-index (will overwrite canvas objects). For instance:

 <Button Name="buttonCancel" Width="80" Height="40" IsCancel="True" Padding="0" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"> <Grid> <Label Padding="0" FontSize="10">Esc</Label> <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">Cancel</Label> <Canvas> <!-- Your Canvas content here --> </Canvas> </Grid> </Button> 
+1
source

Repeating my decision from the comments, because (a) you really do not want the Canvas and (b) it sounds like it solved your problems, so I will make it an answer where it will be more noticeable to others.

Canvas is for fixed-pixel layouts, which is probably the least common case. You should replace the Canvas with a Grid , as shown below, so that both Label dynamically (and independently) laid out within the available space:

 <Grid> <Label Padding="0" FontSize="10">Esc</Label> <Label VerticalAlignment="Center" HorizontalAlignment="Center">Cancel</Label> </Grid> 
0
source

All Articles