Force TextBlock to wrap in WPF ListBox

回眸只為那壹抹淺笑 提交于 2019-11-27 11:51:49
Nash

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!