wpfxamlgridcolumndefinition

How to have WPF Grid columns width="*" but also have a dynamic minimum width so content doesn't get cropped


I have a 3 columns in wpf grid which needs to be proportional

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="2*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Border Grid.Column="0" Background="Yellow"></Border>
    <Border Grid.Column="2" Background="Yellow">
    </Border>
        <Border  Grid.Column="1" Background="Green">
            <Label Content="This is the Green Cell"></Label>
        </Border>
</Grid>

The Result is

enter image description here

The issue is The text in green column is cropped. I can solve the issue by setting MinWidth = "150". But, the green column content will be dynamic, so I can't use value of 150. How can I fix this issue?


Solution

  • I think this does what you want: The Label is how horizontally aligned inside its border, so it sizes naturally to whatever it wants to be instead of stretching to its parent. I gave it a semi-transparent background so you can see which portion of its parent it actually occupies.

    Then we bind Column 1's MinWidth to the ActualWidth of the Label. Column 1 can go as wide as it likes, but it can't get any narrower than the Label.

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition 
                Width="2*" 
                MinWidth="{Binding ActualWidth, ElementName=FixedContent}" 
                />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Border Grid.Column="0" Background="Yellow" />
        <Border Grid.Column="2" Background="Yellow" />
        <Border  Grid.Column="1" Background="Green">
            <Label 
                x:Name="FixedContent"
                HorizontalAlignment="Left"
                Content="This is the Green Cell" 
                Background="#882266aa"
                />
        </Border>
    </Grid>