Dynamically toggle visibility of WPF grid column from C# code

sebi picture sebi · Oct 7, 2013 · Viewed 49.8k times · Source

My problem is: I can't find out how to toggle the visibility of my WPF grid column. Assume following XAML markup:

<Grid x:Name="myGrid">
    <Grid.RowDefinitions>
        <RowDefinition x:Name="Row1" />
        <RowDefinition x:Name="Row2" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="Column1" />
        <ColumnDefinition x:Name="Column2" />
    </Grid.ColumnDefinitions>
</Grid>

Aferwards the grid is filled with some controls etc. Now I want to hide a single column dynamically out of my C# code. I've tried achieving this by setting the the column's definition width to zero, e.g. Column1.Width = 0. This works, but I don't really like this solution - is there really no better way?

I'm looking for something like myGrid.Columns[0].Visibility = COLLAPSED or Column1.Visibility = HIDDEN. I just can't find something like that - any ideas?

Answer

Morlo Mbakop picture Morlo Mbakop · Aug 22, 2018
<ColumnDefinition>
  <ColumnDefinition.Style>
    <Style TargetType="ColumnDefinition">
      <Setter Property="Width" Value="*" />
        <Style.Triggers>
          <DataTrigger Binding="{Binding IsColumnVisible}" Value="False">
            <Setter Property="Width" Value="0" />
          </DataTrigger>
        </Style.Triggers>
    </Style>
  </ColumnDefinition.Style>
</ColumnDefinition>

Please do implement INotifyPropertyChanged in your ViewModel