I need to keep the Grid
cell height = width when resizing.
The working code using a viewBox:
<Viewbox>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Background="Black" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
<Label Grid.Row="1" Grid.Column="0" Background="Gray" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
<Label Grid.Row="0" Grid.Column="1" Background="Gray" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
<Label Grid.Row="1" Grid.Column="1" Background="Black" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
</Grid>
</Viewbox>
Thank's to H.B. for the idea to use a viewBox! :)
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.
WPF provides a UniformGrid
- you might find this more helpful for what you are trying to do. Here is an article that demonstrates it:
http://www.c-sharpcorner.com/UploadFile/yougerthen/308222008124636PM/3.aspx
To keep things square just bind the grid's Width
property to its own ActualHeight
property:
Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
I think you should use a UniformGrid instead, or you can try something like:
<Grid ShowGridLines="True" x:Name="grid" >
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ElementName=grid, Path=RowDefinitions[0].Height}" />
<ColumnDefinition Width="{Binding ElementName=grid, Path=RowDefinitions[1].Height}" />
</Grid.ColumnDefinitions>
</Grid>