0

I am trying to build a 3x3 grid with XAML (for a Windows Phone application) where the center cell should be a square. I have tried the following but it does not work:

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="5*" x:Name="centerColumnDefinition" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="{Binding ElementName=centerColumnDefinition, Path=ActualWidth}" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Canvas Grid.Row="1" Grid.Column="1">
        ...
    </Canvas>
</Grid>

Any suggestions for a working solution?

Greetings from Germany,

Tobias

Tobias J.
  • 1,043
  • 12
  • 31

2 Answers2

0

Try this

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition x:Name="centerColumnDefinition" 
                          Width="5*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Rectangle x:Name="CenterRect"
               Grid.Row="1"
               Grid.Column="1"
               Height="{Binding ElementName=CenterRect,
                                Path=ActualWidth}"
               HorizontalAlignment="Stretch" />
</Grid>

It can be tricky to reference column and row definitions because they are not "real" objects in the visual tree. This method avoids the problem by using a separate object in the center cell that can be used to get the proper sizes.

You should be able to replace the rectangle with another type of control if you want, or just leave it and embed your content inside the rectangle.

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
  • Initially it seems to work. Even the designer shows the nice squared rectangle. But after closing the xaml file and reopening it the height of the Rectangle seems to be zero. Same behavior at runtime. Any further ideas? – Tobias J. Feb 20 '15 at 20:24
0

ActualHeight and ActualWidth are not set until the control is measured and arranged. Usually there is nothing in InitializeComponent() that causes a measure, so you will need to set the Height of your rows after it's calculated. You can do the re-sizing on Loaded event.

Source: https://stackoverflow.com/a/1695518/546896

Community
  • 1
  • 1
ua741
  • 1,446
  • 15
  • 28