anthony
anthony

Reputation: 41098

Conditionally set grid column width

I have a Grid with two columns. I want the leftmost column's width to be either 50% of the available width of the Grid, or the width required to fit any controls contained within the column, whichever is greater. How can I achieve this?

Put differently, I want the column to take up as little width as possible, but with a minimum of 50%.

Upvotes: 1

Views: 2024

Answers (2)

RandomActsOfCode
RandomActsOfCode

Reputation: 3285

Ideally you could set the MinWidth property on the ColumnDefintion to 0.5*. However, this property expects a Double and not a GridLength. To work around this you could take a brute force approach using a converter:

XAML:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" MinWidth="{Binding ElementName=otherColumn, Path=ActualWidth, Converter={l:DivideByTwoConverter}}" />
        <ColumnDefinition x:Name="otherColumn" />
    </Grid.ColumnDefinitions>
    <TextBox Grid.Column="0" />
    <TextBox Grid.Column="1" />
</Grid>

Converter:

public class DivideByTwoConverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is double)
        {
            return (double) value/2;
        }

        return DependencyProperty.UnsetValue;
    }

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

In this example, the column starts out at half the width. As you enter text into the TextBox and it grows, the column too will grow.

Hope this helps!

Upvotes: 2

cordialgerm
cordialgerm

Reputation: 8503

If the width of the parent is known a priori then this is pretty easy. If the parent's width were 100 then:

<Grid>
   <Grid.ColumnDefinitions>
     <ColumnDefinition Width="Auto" MinWidth="50" />
     <ColumnDefinition Width="1*" />
   </Grid.ColumnDefinitions>
</Grid>

Upvotes: -1

Related Questions