Home > database >  How to allow resizable Grid Columns to automatically stretch to remaining space in WPF XAML
How to allow resizable Grid Columns to automatically stretch to remaining space in WPF XAML

Time:02-05

In WPF XAML I cannot seem to get the grid columns to take up the remaining space before a GridSplitter element. It's strange as the vertical one is working and seems to have the exact same set up. I have tried a number of things including using Width="*" and HorizontalAlignment="Stretch" on the column definitions and the left panel Grid itself, but nothing seems to allow it to stretch to the first GridSplitter.

Here is an example of what is happening when using the GridSplitter elements to manually resize:

Example of WPF Grid resizing issue

And here is my XAML:
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" MinWidth="200"></ColumnDefinition>
        <ColumnDefinition Width="4"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <!-- Left Panel -->
    <Grid Grid.Column="0" Background="LightSlateGray">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="4"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <!-- Left Panel | Top -->
        <Grid Grid.Row="0">
            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Padding="10 10 10 10">Test</TextBlock>
        </Grid>
        
        <!-- Left Panel Grid Splitter -->
        <GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch" Background="LightGray" ></GridSplitter>

        <!-- Left Panel | Bottom -->
        <Grid Grid.Row="2">
            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Test</TextBlock>
        </Grid>
    </Grid>

    <!-- Horizontal Grid Splitter -->
    <GridSplitter Grid.Column="1" Height="Auto" Width="4" VerticalAlignment="Stretch" Background="LightGray" ></GridSplitter>

    <!-- Right Panel -->
    <Grid Grid.Column="2">
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Test</TextBlock>
    </Grid>
</Grid>

All I really want is for the first Grid.Column that holds the left panel to resize itself and it's content to cover the remaining space between the left of the window, and the GridSplitter.

Any help would be really appreciated! Thanks

CodePudding user response:

Your "Horizontal Grid Splitter" needs HorizontalAlignment="Center". Actually any value other than Right - which appears to be the default for GridSplitter - works fine.

You would have the same issue in your inner (vertical) splitter if you set VerticalAlignment to Bottom, but this apparently is not the default value.

WPF layout never ceases to keep us on our toes.

  • Related