3

I am trying to fit a wpf grid having 4 cells to be all the time full sized on the screen, having the content of the cells equally split, but i am having problems doing it... This is the code:

    <StackPanel x:Name="MainStackPanel" HorizontalAlignment="Center"  Orientation="Vertical">
    <StackPanel.Resources>
        <Style TargetType="Rectangle">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="Height" Value="Auto"/>
        </Style>
    </StackPanel.Resources>
    <Grid x:Name="Control1" HorizontalAlignment="Center" Height="150">
        <Grid.Resources>
            <Style TargetType="Rectangle">
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="Height" Value="Auto"/>
            </Style>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <Rectangle Fill="Red" Grid.Row="0" Grid.Column="1"/>
        <Rectangle Fill="Blue" Grid.Row="0" Grid.Column="2"/>
        <Rectangle Fill="Green" Grid.Row="1" Grid.Column="2"/>
        <Rectangle Fill="Yellow" Grid.Row="1" Grid.Column="1"/>
    </Grid>
</StackPanel>

Please let me know how should i get this working... or what i am doing wrong...

Clock
  • 974
  • 3
  • 17
  • 35
  • Is it necessary that the Grid is wrapped inside a StackPanel? – Domysee Dec 02 '15 at 19:07
  • I see what you mean (comment below). Based on the setters for the stackpanel it doesn't really seem necessary. The grid standing alone should pretty much appear in this same format, unless the stackpanel also contains other elements not listed. – Danielle Dec 02 '15 at 19:45

2 Answers2

3

If you want to have a grid that has four equally spaced cells then you could do something like this.

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

This will create a 2x2 grid that will automatically resize if the screen is resized. In your example, you have your grid inside of a stack panel so it is only going to fill the size of the stack panel. If you want a grid for the entire screen, you need to put your grid as your first container and set its constraints as shown above.

ProgrammingDude
  • 597
  • 1
  • 5
  • 25
2

You are using the 'Auto' sizing property. In this case if you want it to be equally split and take up the entire space, you'll want to use '*' for both your row and column definitions. Check out the answer that Samuel gives on this related question.

Community
  • 1
  • 1
Danielle
  • 472
  • 4
  • 20