user1205398
user1205398

Reputation: 651

Within a Grid, how to set a textblock's width

I have a Grid, there are two columns, here is the definition.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="180"></ColumnDefinition>
        <ColumnDefinition Width="auto"></ColumnDefinition>
    </Grid.ColumnDefinitions>   
    <TextBlock Name="nText" Text="{Binding Name}" Grid.Column="0" />
    <TextBlock Name="vText" Text="{Binding Value}" Grid.Column="1" HorizontalAlignment="Left" TextWrapping="Wrap"/>
</Grid>

My question is, for the vText, when the Text is too long, the text can not be wrapped, no matter the columndefinition width is auto or *. But if I set a definited value to the column 2 's width or to the vText 's width, the text will be wrapped.

How can I set the textblock's width so that the text content can be wrapped?

I have tried to bind to columnDefinition's width/ActualWidth, but also failed.

Great thanks.

Upvotes: 0

Views: 2823

Answers (2)

ianschol
ianschol

Reputation: 686

To elaborate on BalamBalam's answer, changing

<ColumnDefinition Width="auto"></ColumnDefinition>

to

<ColumnDefinition Width="*"></ColumnDefinition>

will do what you want because "auto" mode expects to infer its size based on the child elements. In this case, your TextBlock doesn't have a Width defined, so there's no way for the ColumnDefinition to infer the width.

Because neither the ColumnDefinition nor the TextBlock have a width defined, the TextBlock's width will default to infinite, and the word wrap algorithm will never clip the text.

By contrast, "*" means to fill remaining space, which will either be defined by the grid (if you set a width on it), or one of its parents. Worst case, the "*" will be able to find a value at the top level, because a window always has a width/height set.

Hopefully this sheds a bit more light on how the layout engine does its magic with sizes!

Upvotes: 1

paparazzo
paparazzo

Reputation: 45096

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="180"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Grid.Row="0" Name="nText" Text="nText"/>
    <TextBlock Grid.Column="1" Grid.Row="0" Name="vText" TextWrapping="Wrap">
        vText vTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvText
        vTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvText
        vTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvTextvText
    </TextBlock>
</Grid>

Upvotes: 0

Related Questions