问题
I need a container with square shape, but it has to be as big as it cans, but without be bigger of the parent.
I tried with the choosen answer from here: WPF dynamic layout: how to enforce square proportions (width equals height)?
but it creates a square bigger than the parent, what I need is a square that fits with the parent (like when you put in an image Stretch=Uniform).
回答1:
You could try something like this:
<Grid x:Name="outer" Background="Cyan" Width="200" Height="400">
<Grid Background="Red" HorizontalAlignment="Stretch" Height="{Binding Path=ActualWidth, ElementName=outer}">
</Grid>
</Grid>

回答2:
I figured out a way to make the square smaller than the parent by using MaxWidth
and MaxHeight
.
<Grid Background="Blue">
<Grid Background="Red"
MaxWidth="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType=Grid}}"
MaxHeight="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType=Grid}}">
</Grid>
</Grid>
The parent Grid
fits the whole screen, and the child Grid
keeps its aspect ratio even on rotation.
EDIT :
Or simply use ViewBox
<Grid Background="Blue">
<Viewbox Stretch="Uniform">
<Grid Background="Red" MinWidth="1" MinHeight="1">
</Grid>
</Viewbox>
</Grid>
You can use this for any aspect ratio by changing the MinWidth
and MinHeight
of the inner Grid
来源:https://stackoverflow.com/questions/29620938/windows-phone-xaml-force-square-proportioned-container-aspectratio-11