Home > Enterprise >  How to Add and Remove specific columns from Grid?
How to Add and Remove specific columns from Grid?

Time:03-22

I'm trying to remove a specific column/row when the window ActualWidth and ActualHeight is over 700. I couldn't really find a way to remove a specific column/row besides

myGrid.ColumnDefinitions.RemoveAt(1);

which removes one column everytime the widow size changes.

Current Grid:

<Grid x:Name="myGrid">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition MaxHeight="80" MinHeight="80"/>
        <RowDefinition MaxHeight="80" MinHeight="80"/>
        <RowDefinition MaxHeight="80" MinHeight="80"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions >
        <ColumnDefinition MaxWidth="170" MinWidth="170" x:Name="ColumnThatNeedsToBeRemovedAndReadded"/>
        <ColumnDefinition MinWidth="110" Width="*"/>
        <ColumnDefinition MinWidth="350" MaxWidth="700"/>
        <ColumnDefinition MinWidth="170" Width="*"/>
    </Grid.ColumnDefinitions>
</Grid>

Code which Adds/Removes:

 if (ActualHeight > 700 && ActualWidth > 700)
 {
    myGrid.ColumnDefinitions.RemoveAt(1);
 }
 else if(ActualHeight < 700 && ActualWidth > 700)
 {
    myGrid.ColumnDefinitions.Add(new ColumnDefinition());
 }

CodePudding user response:

Instead of completely removing the column, you could shrink it to zero width.

var columnDefinition = myGrid.ColumnDefinitions[0];

if (ActualHeight > 700 && ActualWidth > 700)
{
   columnDefinition.MinWidth = 0;
   columnDefinition.Width = new GridLength(0);
}
else if (ActualHeight <= 700 && ActualWidth > 700)
{
   columnDefinition.MinWidth = 170;
}

CodePudding user response:

You can do something like this to remove a specific column:

   for (var index = 0; index < myGrid.ColumnDefinitions.Count; index  )
    {
        var currentCol = myGrid.ColumnDefinitions[index];
        if (currentCol.ActualWidth > 700)
        {
            myGrid.Children.RemoveAt(index);
        }
    }
  • Related