强制文本块包装在 WPF 列表框中

我有一个显示消息的 WPF 列表框。它在左侧包含一个头像,用户名和消息垂直堆叠在头像的右侧。在消息文本应该换行之前,布局是很好的,但是我在列表框上得到了一个水平滚动条。

我在谷歌上搜索,找到了类似问题的解决方案,但没有一个奏效。

<ListBox HorizontalContentAlignment="Stretch"  ItemsSource="{Binding Path=FriendsTimeline}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border BorderBrush="DarkBlue" BorderThickness="3" CornerRadius="2" Margin="3" >
<Image Height="32" Width="32"  Source="{Binding Path=User.ProfileImageUrl}"/>
</Border>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=User.UserName}"/>
<TextBlock Text="{Binding Path=Text}" TextWrapping="WrapWithOverflow"/> <!-- This is the textblock I'm having issues with. -->
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
54794 次浏览

The problem might not be located in the ListBox. The TextBlock won't wrap, if one of the parent controls provides enough space, so that it hasn't the need to wrap. This might be caused by a ScrollViewer control.

Contents of the TextBlock can be wrapped using property TextWrapping. Instead of StackPanel, use DockPanel/Grid. One more thing - set ScrollViewer.HorizontalScrollBarVisibility property to Disabled value for the ListBox.

Updated Hidden to Disabled based on comment from Matt. Thanks Matt.

If you want to prevent TextBlock to grow, and you want it to just fit in the size of the listbox, you should set the width of it explicitly.

In order to change it dynamically, it means not a fix value, but you need to bind it to its proper parent element in the visual tree. You can have something like this:

<ListBox ItemsSource="{Binding MyItems}" Name="MyListBox">


<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Width"
Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ScrollContentPresenter}, Path=ActualWidth}" />
</Style>
</ListBox.Resources>


<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" TextWrapping="Wrap" />
</DataTemplate>
</ListBox.ItemTemplate>


</ListBox>

If it does not work, try to find the proper elements (which has to be binded to what) with the Live Visual Tree in Visual Studio.