Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grid content expand to fill container when other content is collapsed?

Tags:

wpf

xaml

I have a window with this basic layout:

<Window x:Class="GridStuffs.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.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Button Grid.Row="0" Click="TopButtonClick" VerticalAlignment="Stretch">Top</Button>
    <Button Grid.Row="1" Name="_bottomButton">Bottom</Button>
</Grid>

Which is just displaying two buttons 'top' and 'bottom', each taking up equal vertical space in the window.

Clicking the top button executes the following:

private void TopButtonClick(object sender, RoutedEventArgs e)
{
    if (_bottomButton.Visibility == Visibility.Collapsed)
    {
        _bottomButton.Visibility = Visibility.Visible;
    }
    else
    {
        _bottomButton.Visibility = Visibility.Collapsed;
    }
}

...which toggles the Visibity of the bottom button between Collapsed and Visible.

What I want to happen is have the top button resize to fill the window when the bottom button is collapsed. What's actually happening is the bottom button is hidden, but the top button retains it's original size.

Question: What wpf/xaml magic do I have to do to have the top button expand to fill the window when the bottom button is collapsed?

like image 261
Pj. Avatar asked Aug 09 '12 14:08

Pj.


1 Answers

Set the top RowDefinition to Height="*", meaning it will take up all available space, and set the second RowDefinition to Height="Auto" meaning it will take up as much space as it needs to show its content,

<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="Auto" />
</Grid.RowDefinitions>

In the event that your 2nd Button's height is not defined and should be 50% of the Grid's height, I would use a converter to bind the Button.Height property to half of the parent Grid's height

<Button Height="{Binding ActualHeight, 
    RelativeSource={RelativeSource Grid}, 
    Converter={StaticResource HalfOfValueConverter}}" />

If you're interested, I actually have a MathConverter posted on my blog that I use for any kind of mathematical equations with a bound value.

<Button Height="{Binding ActualHeight, 
    RelativeSource={RelativeSource Grid}, 
    Converter={StaticResource MathConverter},
    ConverterParameter=@VALUE/2}" />
like image 192
Rachel Avatar answered Nov 02 '22 23:11

Rachel