Question

I'm trying to hide first 2 columns of a Grid when a Button is clicked. My Grid layout has 3 columns, one with a grid, the second with a grid splitter and the third one with another Grid which has the Button.

When I run my program with the below code, it collapses the first 2 columns on click of the Button properly as expected and resizes the third grid, however the moment I resize the grid using the splitter, this does not work anymore. It hides the columns, however the third column is not resized to fill the Window. I want the first 2 columns to be collapsed and the third column to fill the whole area of the window(which happens if I do not resize using the splitter).

The xaml is as below:

<Grid>
    <ColumnDefinition Width="Auto" x:Name="column1"/>
    <ColumnDefinition Width="Auto" x:Name="column2"/>
     <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<Grid Grid.Column="0" x:Name="left" MinWidth="100">
    <Border Background="Red" Margin="5"/>
    <TextBlock Text="A Brown fox jumped oversomething" Width="{Binding ActualWidth, ElementName=TreeView}" Margin="5"></TextBlock>
</Grid>

<GridSplitter x:Name="splitter"
            Width="5"
            Grid.Column="1"
            HorizontalAlignment="Left"
            Margin="0,5,0,5"
            Panel.ZIndex="1"
            VerticalAlignment="Stretch"                
            ResizeDirection="Columns"/>

<Grid Grid.Column="2">        
    <Grid Grid.Column="0" Grid.Row="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="20"></RowDefinition>
        </Grid.RowDefinitions>
        <Border Grid.Row="0" Background="Green" Margin="5"/>
        <Button Grid.Row="1" Click="OnClick">HideAndResize</Button>
    </Grid>
</Grid>
</Grid>

and the Button.click event is handled as below:

private bool clicked;

private void OnClick(object sender, RoutedEventArgs e)
{
    clicked = !clicked;

    left.Visibility = clicked ? Visibility.Collapsed : Visibility.Visible;
    splitter.Visibility = clicked ? Visibility.Collapsed : Visibility.Visible;

}
Was it helpful?

Solution

Seems like the Column isnt autosizing correctly, so its still not 0, even if it's childs Visibility is set to Collapsed.

A quick and dirty solution would be:

    private bool clicked;
    private double oldLenght;
    private void OnClick(object sender, RoutedEventArgs e)
    {
        clicked = !clicked;

        splitter.Visibility = clicked ? Visibility.Collapsed : Visibility.Visible;
        left.Visibility = clicked ? Visibility.Collapsed : Visibility.Visible;
        oldLenght = clicked ? column1.ActualWidth : oldLenght;
        column1.Width = clicked ? new GridLength(0.0) : new GridLength(oldLenght);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top