强制TextBlock包装在WPF ListBox中

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

我谷歌search,find类似的问题的解决scheme,但没有一个工作。

<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> 

TextBlock内容可以使用属性TextWrapping 。 使用DockPanel / Grid代替StackPanel 。 还有一件事 – 将ScrollViewer.HorizontalScrollBarVisibility属性设置为ListBox Disabled值。

基于来自Matt的评论,将Hidden更新为Disabled 。 谢谢Matt。

问题可能不在列表框中。 如果其中一个父控件提供了足够的空间,那么TextBlock将不会打包,所以它不需要打包。 这可能是由ScrollViewer控件造成的。

如果要防止TextBlock增长,并且希望它适合列表框的大小,则应该明确设置它的宽度。

为了dynamic改变它,它不是一个固定值,但是你需要将它绑定到它在视觉树中的适当的父元素。 你可以有这样的东西:

 <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> 

如果不起作用,请尝试使用Visual Studio中的实时可视化树来查找适当的元素(必须将其绑定到哪个元素上)。