Wpf – XAML TextBlock: How to make TextBlock have variable height

listboxtextblockwpfxaml

I have a ListBox that contains TextBlocks.

Sometimes the content of a TextBlock is too long and I want the height of this entry to double or triple as needed to accommodate the text.

I tried TextWrapping="Wrap" but it doesn't work. Every TextBlock is still just one line in height.

Is there an easy way to fix the problem in XAML? Thanks.

* Additional info: I tried to simplify the question but perhaps the complete scenario is better.

  1. I have a listbox whose entries are displayed according to a template in code below.
  2. Each entry has 2 pieces of info: a product price followed by product name.
  3. I don't want to use the horizontal scrollbar in the listbox and want the product name to be displayed in 2 or more lines if necessary. The product name is the 2nd TextBlock.

Here's my XAML:

<ListBox Name="listBox1" ItemsSource="{Binding}" Margin="10" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock MinWidth="40"  TextAlignment="Right" Text = "{Binding ProductPrice}" />


                    <TextBlock Text = "{Binding ProductName}" TextWrapping="Wrap" />

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>

Best Answer

Disable the listbox horizontal scrollViewer. This way the textBlock will be forced to wrap.

XAML:

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
      <TextBlock TextWrapping="Wrap"/>
</ListBox>

Example result:

enter image description here

Edit:

From the XAML you added I'm confident that the problem lays in the StackPanel. Try replacing it with Grid for example:

    <ListBox Name="listBox1" ItemsSource="{Binding}" Margin="10" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemTemplate>
                <DataTemplate>
                   <Grid>
                     <Grid.ColumnDefinitions>
                         <ColumnDefinition Width="*"/>
                         <ColumnDefinition Width="*"/>
                     </Grid.ColumnDefinitions>
                        <TextBlock MinWidth="40"  TextAlignment="Right" Text = "{Binding ProductPrice}" />


                        <TextBlock Grid.Column="1" Text = "{Binding ProductName}" TextWrapping="Wrap" />

                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>

        </ListBox>

StackPanel doesn't limit the content size, therefore the textBlock doesn't knows where the space ends , and the wrapping doesn't happens.

Related Topic