Search code examples
c#wpfclipping

Grid ignores ClipToBounds in WPF


Given a really basic Grid, with ColumnDefinition's width set to *, the hardcoded width attribute of the button's contained within are ignored and these child elements are clipped. They are not clipped with a width set to Auto.

This clipping is prevented if correct MinWidths are set on each ColumnDefinition, but this is not exactly dynamic.

Am I doing things wrong or is this the best WPF has to offer?

enter image description here

becomes

enter image description here

Markup:

    <Grid ShowGridLines="True" ClipToBounds="False">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
            <Button Grid.Column="0" Width="120">AAAAA</Button>
            <Button Grid.Column="1" Width="120">BBBB</Button>
            <Button Grid.Column="2" Width="120">CCCCC</Button>
    </Grid>

I would like the buttons to appear as per the first image when there is room, and as image three when there is none (i.e. no clipping under any circumstances).

enter image description here


Solution

  • Ahh I've solved it as follows:

    The key is the MinWidth attribute in the ColumnDefinition.

     <Grid ShowGridLines="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition MinWidth="{Binding Path=ActualWidth, ElementName=spLeft }"></ColumnDefinition>
                <ColumnDefinition MinWidth="{Binding Path=ActualWidth, ElementName=spMid }"></ColumnDefinition>
                <ColumnDefinition MinWidth="{Binding Path=ActualWidth, ElementName=spRight }"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <StackPanel Background="Red" Grid.Column="0" Name="spLeft" HorizontalAlignment="Center">
                <Button  Width="120">AAAAA</Button>
            </StackPanel>
            <StackPanel Background="Green" HorizontalAlignment="Center" Grid.Column="1" Name="spMid">
                <Button  Width="120">BBBB</Button>
            </StackPanel>
            <StackPanel Background="Blue" Name="spRight" Grid.Column="2" HorizontalAlignment="Center">
                <Button  Width="120">CCCCC</Button>
            </StackPanel>
        </Grid>