prabhat
prabhat

Reputation: 87

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?

Upvotes: 1

Views: 1923

Answers (2)

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>

Upvotes: 1

kennyzx
kennyzx

Reputation: 13003

If you want to wrap the text, use TextBlock instead of Label. Label does not support Text Wrapping.

<Border Grid.Column="1" Background="Green">
    <TextBlock TextWrapping="Wrap" Text="This is the Green CellThis is the Green CellThis is the Green CellThis is the Green Cell"/>
</Border>

Upvotes: 1

Related Questions