Poma
Poma

Reputation: 8474

How to bind Grid row height?

I have 2 identical grids with splitters:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button Grid.Row="0" />
    <Button Grid.Row="2" />
    <GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch" />
</Grid>

How to make them resize synchronously? So that row heights will be the same for both grids.

Upvotes: 3

Views: 7878

Answers (3)

Dmitry
Dmitry

Reputation: 3107

You need to use Shared Size Groups. Add an attribute SharedSizeGroup="some_label" to row or column definitions you want to resize synchronously.

Also, you need to define Grid.IsSharedSizeScope="true" for some container which contains both grids (tab control in your case).

Upvotes: 2

Poma
Poma

Reputation: 8474

Looks like I can do that via simple bindings:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="{Binding Path=MySize, Mode=TwoWay}" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button Grid.Row="0" />
    <Button Grid.Row="2" />
    <GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch" />
</Grid>

Where MySize is

private GridLength mySize;
public GridLength MySize
{
    get { return mySize; }
    set
    {
        if (mySize == value) return;
        mySize = value;
        OnPropertyChanged("MySize");
    }
}

Note: Mode=TwoWay is needed since unlike other conrols RowDefinition doesn't default its mode to TwoWay

Upvotes: 2

SvenG
SvenG

Reputation: 5195

I think the only way to accomplish that is programmatically:

Register the DragCompleted Event of the Gridsplitter in both grids in XAML and give each grid a name:

<GridSplitter DragCompleted="GridSplitter_DragCompleted1" Grid.Row="1" Height="4" HorizontalAlignment="Stretch" />

In CodeBehind sync the height of the RowDefinitions. As the grisplitter is only affecting the Row/ColDefinitions of the attached rows/cols, we have to sync the rowdefinitions here. Doing other things like setting the gridsplitters position won't work.

private void GridSplitter_DragCompleted1(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
  SyncRowDefinitions(Grid1, Grid2);
}

private void GridSplitter_DragCompleted2(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
  SyncRowDefinitions(Grid2, Grid1);
}


private void SyncRowDefinitions(Grid sourceGrid, Grid targetGrid)
{
  for (int i = 0; i < sourceGrid.RowDefinitions.Count; i++)
  {
    targetGrid.RowDefinitions[i].Height = sourceGrid.RowDefinitions[i].Height;
  }
}

Edit: If needed you can Sync the grids also on other occurences like sizechanged (of the overall grid) after its initially loaded, and so on ...

Upvotes: 0

Related Questions