Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF GridSplitter strange behavior when Column Width="Auto"

I have pretty simple layout, look:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" MinWidth="200"></ColumnDefinition>
        <ColumnDefinition Width="5"></ColumnDefinition>
        <ColumnDefinition Width="Auto" MinWidth="50"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Border Grid.Column="0"
            BorderBrush="Red"
            BorderThickness="2">
        <!-- Any picture-->
        <Image Source="/Resources/PreviewTest.png"></Image>
    </Border>
    <GridSplitter Grid.Column="1" 
                    Width="5"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Stretch"
                    ResizeBehavior="PreviousAndNext"></GridSplitter>
    <Expander Grid.Column="2"
                ExpandDirection="Left"
                BorderBrush="RoyalBlue"
                BorderThickness="2">
        <!-- Any picture-->
        <Image Source="/Resources/PreviewTest.png"></Image>    
    </Expander>
</Grid>

The problem: when I'm dragging GridSplitter to left, right column goes out from window border as shown on animation. I found that it happens when width of third column is set as "Auto" (Width="Auto"). If I set Width="*" GridSplitter works fine and third Column doesn't go out from window border. So why when Width="Auto" it happens?

Demonstration

like image 229
monstr Avatar asked Jun 26 '14 06:06

monstr


1 Answers

Your problem is caused by the fact that one of your ColumnDefinitions is set to Auto. What is happening is that when the first column reaches its MinWidth value, it can't get any smaller. However, if you keep moving the GridSlitter, then the right column has to grow. Seeing as you let it grow to any size, you get your current problem.

All that you need to do to fix it is to set the right ColumnDefinition.Width property to the * value as well. In this way, it can't grow out of the Grid any more. If you need to, you can control the end sizes of the columns using the ColumnDefinition.MaxWidth property. Try this:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" MinWidth="200" />
        <ColumnDefinition Width="5" />
        <ColumnDefinition Width="*" MinWidth="50" />
    </Grid.ColumnDefinitions>
    <Border Grid.Column="0" BorderBrush="Red" BorderThickness="2">
        <Image Source="/Resources/PreviewTest.png" />
    </Border>
    <GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Center" VerticalAlignment="Stretch" ResizeBehavior="BasedOnAlignment" />
    <Expander Grid.Column="2" ExpandDirection="Left" BorderBrush="RoyalBlue" BorderThickness="2">
        <Image Source="/Resources/PreviewTest.png" />
    </Expander>
</Grid>
like image 53
Sheridan Avatar answered Nov 08 '22 00:11

Sheridan