How to collapse a star sized grid column in WPF?

Viewed 2632

Getting three columns have the same width is done by setting Width to Auto.

<Grid x:Name="myGrid">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <Label Grid.Row="0" Grid.Column="0">One</Label>
  <Label Grid.Row="0" Grid.Column="1" x:Name="label1">Two</Label>
  <Label Grid.Row="0" Grid.Column="2">Three</Label>
</Grid>

I want to achieve that if middle column is collapsed or hidden that the other two take up remaining space and get equal width.

If I just set Visibility to Collapsed or Hidden because of the Width="*", the other two columns width stays the same.

<Label Grid.Row="0" Grid.Column="1" Visibility="Collapsed">Two</Label>

enter image description here

I achieved desired functionality by programatically setting second column width to auto, but am looking for some other solution (preferably xaml way one).

private void Button_Click(object sender, RoutedEventArgs e)
{
  this.myGrid.ColumnDefinitions[1].Width = GridLength.Auto;
  this.label1.Visibility = Visibility.Collapsed;
}
2 Answers

The desired behaviour can be achieved using a UniformGrid.

Make sure to set the number of rows to 1.

<UniformGrid Rows="1">
    <Label>One</Label>
    <Label>Two</Label>
    <Label>Three</Label>
</UniformGrid>

3 cols

The remaining elements are evenly spaced.

<UniformGrid Rows="1">
    <Label>One</Label>
    <Label Visibility="Collapsed">Two</Label>
    <Label>Three</Label>
</UniformGrid>

2 cols

I added Xaml Binding as suggested by Rob like this:

<Grid.ColumnDefinitions>
  <ColumnDefinition Width="*" />
  <ColumnDefinition Width="{Binding MiddleColumnWidth}" />
  <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Label Grid.Row="0" Grid.Column="0">One</Label>
<Label Grid.Row="0" Grid.Column="1" Visibility="{Binding IsSecondLabelVisible}">Two</Label>
<Label Grid.Row="0" Grid.Column="2">Three</Label>

Code behind xaml:

private bool ShowOnlyTwoColumns;

private GridLength MiddleColumnWidth
{
  get
  {
    if (ShowOnlyTwoColumns)
      return GridLength.Auto; // Auto collapses the grid column when label is collapsed

    return new GridLength(1, GridUnitType.Star);
  }
}

private Visibility IsSecondLabelVisible
{
  get { return this.ShowOnlyTwoColumns ? Visibility.Collapsed : Visibility.Visible; }
}
Related