Search code examples
wpftemplatesitemscontroltextblockword-wrap

Why is a Border needed around a TextBlock in an ItemsControl template to make the TextBlock wrap?


I found this question while trying to figure out how to make a TextBlock wrap, when that TextBlock is the template for each item in an ItemsControl.

My original template:

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Grid>
            <TextBlock Padding="2" x:Name="SummaryRow" Text="{Binding}" TextWrapping="Wrap" />
        </Grid>
    </DataTemplate>
</ItemsControl.ItemTemplate>

In order to make the text actually wrap, I had to surround the TextBlock with a Border. I'm sure other containers would have worked as well.

Why is this? (btw I should mention that the ItemsControl is in a ScrollViewer)


Solution

  • For the text to be wrapped you need to restrict the size of the textBlock so as to wrap the text once it exceeds that restricted limit. But since your textBlock have scrollViewer outside, it has no restiction on its size and hence no wrap. You need to set the HorizontalScrollBarVisbility to Collapsed or Hidden to restrict the size and hence wrapping of text.