wpf

How to keep grid cell height and width the same


I need to keep the Grid cell height equal to width when resizing:

<Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="{Binding ElementName=RowDefinition, Path=Height}"/>
            <ColumnDefinition Width="{Binding ElementName=RowDefinition, Path=Height}"/>
        </Grid.ColumnDefinitions>
</Grid>

The cells have to stay perfectly squared when resizing.


Solution

  • The "proper" way to do this is probably using the shared-size features of the Grid control, but this sadly prevents stretching the whole grid. e.g.

    <Grid Grid.IsSharedSizeScope="True">
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="A"/>
            <ColumnDefinition SharedSizeGroup="A"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition SharedSizeGroup="A"/>
            <RowDefinition SharedSizeGroup="A"/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="0" Background="Red"   Content="Lorem"/>
        <Label Grid.Row="1" Grid.Column="0" Background="White" Content="Lorem ipsum"/>
        <Label Grid.Row="0" Grid.Column="1" Background="White" Content="Lorem ipsum dolor"/>
        <Label Grid.Row="1" Grid.Column="1" Background="Red"   Content="Lorem ipsum dolor sit"/>
    </Grid>
    

    One could place this in a Viewbox but the resize behavior of that is probably not what you want, since it zooms the contents. Maybe you can find a way to make this usable in your context.