0

I have a grid, with several rows. I have a user control, which I place on one of the rows, with a rowspan of 2. All the rows have the same hight. I set the vertical alignment of the user control to center, so it appears in the middle of the two rows. What I want is for the user control to have a height of 1 of the rows of the grid, regardless of the height of the grid. So in effect the user control will grow in height relative to the height of the row in the grid, because the row hight is also relative to the grid height.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
Jeremy
  • 44,950
  • 68
  • 206
  • 332

2 Answers2

1

It seems like you might want to data bind the height of the user control to the height of the RowDefinition. This question is somewhat similar but he's binding the row height, not a contained element: How do I databind a ColumnDefinition's Width or RowDefinition's Height?

I tried a simple approach which may be frowned upon but may suit your needs.

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid ShowGridLines="True">  
    <Grid.RowDefinitions>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>

    <Rectangle x:Name="measurementRect" VerticalAlignment="Stretch" Grid.Row="1" Fill="Blue" Width="1" Visibility="Hidden" />
    <Rectangle Grid.Row="2" Grid.RowSpan="2"
      VerticalAlignment="Center" Fill="Green" Height="{Binding ElementName=measurementRect,Path=ActualHeight}" Width="200" />
  </Grid>
</Page>
Community
  • 1
  • 1
jschroedl
  • 4,916
  • 3
  • 31
  • 46
0

I first thought databinding the height of your user control to the height of the row through a common property might work, however it occured to me that you cannot bind the height of a row as RowDefinition subclasses DependencyObject, but the SetBinding method is defined in FrameworkElement.

That said, one option may be to programatically find the height of the row and bind the control height to that.

Example Property

private int controlHeight;
public int ControlHeight
{
  get 
  {
     int row = Grid.GetRow(this.myControl);
     return myGrid.RowDefinitions[row].Height;
   }
   set
   {
       controlHeight = value;
       //Implement property changed event etc here if needed
    }
 } 

If you want to ensure that the control size will scale dynamically (other than on load), additional code will be needed to update the property and notify the UI. You could also check the height of the grid and divide by the number of columns in this property, although that might not be as scalable.

Note because you are using colSpan you may need to divide the row height by 2.

PortageMonkey
  • 2,675
  • 1
  • 27
  • 32