Search code examples
wpfexpandergrid-layout

Link Expander action to RowDefinition height


I have the following grid:

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

                <Expander Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
                    <TextBox />
                </Expander>

The text box fills the expander. I would like to set this up such that when the bottom row is expanded, the row heights are Auto / * / *, and when the bottom is collapsed, the row heights are Auto / * / Auto. I've tried (without success) at using style triggers to do this, and would like to do this in XAML instead of code as much as possible. Thanks in advance...


Solution

  • So far this is my ugly workaround:

    <Window.Resources>
        <Style TargetType="Expander">
            <EventSetter Event="Expanded" Handler="ExpanderGrow"/>
            <EventSetter Event="Collapsed" Handler="ExpanderGrow"/>
        </Style>
    </Window.Resources>
    

    ...and the CS required:

        public void ExpanderGrow(object sender, RoutedEventArgs e)
        {
            Expander expander = (Expander)sender;
            Grid grid = (Grid)expander.Parent;
            int index = Grid.GetRow(expander);
            RowDefinition rowdef = grid.RowDefinitions[index];
    
            rowdef.Height = new GridLength(1,
                expander.IsExpanded ? GridUnitType.Star : GridUnitType.Auto);
        }