wpfwpf-grid

Grid with RowDefinitions based on content


I am trying to get something like an image with adjustable margins done. The image itself is actually a path and resides in a StackPanel, stretching vertically. The StackPanel's width can be adjusted, and I want to keep the image's ratio and the ratio of path size to margin.

<StackPanel>
  <Grid HorizontalAlignment="Stretch">
    <Grid.RowDefinitions>
      <RowDefinition Height="0.25*"/>
      <RowDefinition Height="0.5*"/>
      <RowDefinition Height="0.25*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="0.25*"/>
      <ColumnDefinition Width="0.5*"/>
      <ColumnDefinition Width="0.25*"/>
    </Grid.ColumnDefintions>

    <Path Grid.Row="1"
          Grid.Column="1"
          Data="...blabla..."
          Fill="#FF0072C6"
          Stretch="UniformToFill"/>
  </Grid>
</StackPanel>

Now, the problem is, even though the path object gets drawn in the grid, the first and third rows are always of zero height, instead of getting set based on the height of the 2nd row. I know this happens because the Grid resides in a StackPanel, which ignores automatic height settings and doesn't even let the Grid stretch vertically (or horizontally depending on orientation). It does work if I set a fixed height to the grid but that would ruin the aspect ratio of the image when resizing. How can I get this to work?

This is what I have:

zero height rows

This is what I want:

supposed height rows

EDIT:

It seems there is confusion concerning my question. So to hopefully clarify, here's the desired result after resizing the StackPanel:

supposed result after resize

As you can see, the whole grid is supposed to resize like it was an actual image. The Grid should keep its aspect ratio. This is not about the Path inside the Grid.


Solution

  • If i have correctly understood the problem, a simple solution could be fixing sizes and using a viewbox:

    <StackPanel>
    
    <!--The other rows-->
    
        <Viewbox>
            <Grid Width="100" Height="100">
                <Grid.RowDefinitions>
                    <RowDefinition Height="25"/>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="25"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="25"/>
                    <ColumnDefinition Width="50"/>
                    <ColumnDefinition Width="25"/>
                </Grid.ColumnDefinitions>
                <Path Grid.Row="1"  Grid.Column="1"   Data="M8.5,13.5L11,16.5L14.5,12L19,18H5M21,19V5C21,3.89 20.1,3 19,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19Z" Fill="Blue" Stretch="Uniform" />
            </Grid>
        </Viewbox>
    </StackPanel>