Search code examples
wpfxamlgridviewbox

How to make contents having equal space (width & hight) to resize upon changing of window size in XAML?


I have the following code of XAML in WPF. This generates the grid with equal size of columns & rows (as shown in figure 1.)

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
     </Grid.ColumnDefinitions>

     <TextBlock Grid.Row="0" Grid.Column="0"  Text="A" Background="Green"/>
     <TextBlock Grid.Row="1" Grid.Column="1"  Text="AB" Background="Red"/>
     <TextBlock Grid.Row="2" Grid.Column="2"  Text="ABC" Background="Blue"/>
     <TextBlock Grid.Row="3" Grid.Column="3"  Text="ABCD" Background="Yellow"/>
</Grid>

Figure 1.

Figure 1.

But when I put this grid in a viewbox (like the code below), the rows & column remains no more equally in size (as shown in figure 2.).

<Viewbox  Stretch="Uniform">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Row="0" Grid.Column="0"  Text="A" Background="Green"/>
        <TextBlock Grid.Row="1" Grid.Column="1"  Text="AB" Background="Red"/>
        <TextBlock Grid.Row="2" Grid.Column="2"  Text="ABC" Background="Blue"/>
        <TextBlock Grid.Row="3" Grid.Column="3"  Text="ABCD" Background="Yellow"/>

    </Grid>
</Viewbox>

Figure 2.

Figure 2.

How can I make this grid with equal size of rows & column inside a viewbox?


Solution

  • You can enforce size-sharing like this:

    <Grid Grid.IsSharedSizeScope="True">
        <Grid.RowDefinitions>
            <RowDefinition SharedSizeGroup="A"/>
            <RowDefinition SharedSizeGroup="A"/>
            <RowDefinition SharedSizeGroup="A"/>
            <RowDefinition SharedSizeGroup="A"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="B"/>
            <ColumnDefinition SharedSizeGroup="B"/>
            <ColumnDefinition SharedSizeGroup="B"/>
            <ColumnDefinition SharedSizeGroup="B"/>
        </Grid.ColumnDefinitions>