joe_coolish
joe_coolish

Reputation: 7259

WPF Square auto-size to parent container

I have a UniformGrid object in my WPF project that has 2 rows and 3 cols and its width and height are set to auto (with both alignments set to Stretch).

This grid will hold 6 squares that I want to fill as much of their cell as possible and be centered horizontally and vertically.

What do I need to be added to allow for the squares to increase/decrease their length/width based on the dynamic size of the parent? I.E., when the window is resized.

Here is my xaml so far:

    <UniformGrid Rows="2" Columns="3">
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
    </UniformGrid>

Edit:

And the Rectangle objects need to remain square.

Upvotes: 3

Views: 12191

Answers (3)

Emond
Emond

Reputation: 50682

You could do this:

<UniformGrid.Resources>
    <Style TargetType="Rectangle">
        <Setter Property="Width"
                Value="{Binding RelativeSource={RelativeSource Mode=Self},Path=ActualHeight}" />
    </Style>
</UniformGrid.Resources>

Or you could bind the Height to the ActualWidth.

Unfortunately this will not keep them stretched to the maximum.

Upvotes: 1

Wegged
Wegged

Reputation: 2423

If you remove the height and width properties it will do just that.

Upvotes: -1

Wegged
Wegged

Reputation: 2423

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
  <Grid>
<UniformGrid Rows="2" Columns="3">
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
    </UniformGrid>
  </Grid>
</Page>

Upvotes: 4

Related Questions