Vahid
Vahid

Reputation: 5444

Collapse a Grid in WPF

I'm using the below code to create a 3 column layout with grids.

<Window x:Class="WpfApplication21.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid Column="0" Background="Aqua"></Grid>
        <Grid Column="1" Background="Red"></Grid>
        <Grid Column="2"  Background="Yellow"></Grid>
    </Grid>
</Window>

enter image description here

The part I don't understand is that when I set the Visibility of the third grid to Collapsed the space it takes is still there. I want the remaining space to be added to other two grids.

<Grid Column="2" Background="Yellow" Visibility="Collapsed"></Grid>

enter image description here

Upvotes: 3

Views: 5896

Answers (2)

Bolu
Bolu

Reputation: 8786

You are telling Grid to equally divide itself into 3 parts, you need to set the last column to Auto width to achieve what you want (to make the last column to match the width of its content):

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

Upvotes: 5

Sajeetharan
Sajeetharan

Reputation: 222522

Since you are hiding only the ColumnDefinition of the Grid, but you are not actually hiding the Grid.

You can do something like this, To hide the Third Column, you need to set the width of the column to be "0"

   <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition  x:Name="TestColumn"  Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid Column="0" Background="Aqua"></Grid>
        <Grid Column="1" Background="Red"></Grid>
       <Button Grid.Column="2" Click="hideColumn">hideColumn</Button>
    </Grid>

 private void hideColumn(object sender, RoutedEventArgs e)
        {
            this.TestColumn.Width = new GridLength(0, GridUnitType.Pixel);
        }

Upvotes: 1

Related Questions