#1,197 – Autosizing in a Grid with Maximum Size

You can use autosizing for grid rows or columns to have the row or column automatically size to fit its contents. There are times, however, when you want the row or column to fit its contents, but only up to a limit. E.g. Autosize a row height, but only to a maximum of 20% of the size of the entire grid.

You can autosize within limits by using the MaxHeight attribute and a value converter.

Below, we have a grid with two rows, each containing a ListBox. The second row is set to autosize and the first to use all remaining space.

        <local:MaxHeightConverter x:Key="MaxHeightConverter"/>
        <sys:Double x:Key="adjMaxHeightRatio">0.2</sys:Double>

<Grid x:Name="grdRoot">
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>

    <ListBox Grid.Row="0" ItemsSource="{Binding Dogs}" />

    <ListBox Grid.Row="1" ItemsSource="{Binding MoreDogs}" MaxHeight="{Binding ElementName=grdRoot, Path=ActualHeight, Converter={StaticResource MaxHeightConverter}, ConverterParameter={StaticResource adjMaxHeightRatio}}" />

The second ListBox will take as much room as it needs (grow to fit all elements), until it reaches 20% of the height of the parent grid. At that point, it will be constrained and get a vertical scrollbar.

Here’s the code for the converter:

public class MaxHeightConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        double pctHeight = (double)parameter;

        if ((pctHeight <= 0.0) || (pctHeight > 100.0))
            throw new Exception("MaxHeightConverter expects parameter in the range (0,100]");

        return ((double)value * pctHeight);

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        throw new NotImplementedException();

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #1,197 – Autosizing in a Grid with Maximum Size

  1. Julien Barbier says:

    Is it a restart of the series ? 🙂

  2. Pingback: Dew Drop - November 30, 2016 (#2373) - Morning Dew

  3. Sean says:

    No, unfortunately not. Just a random thought. :O)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: