首页 文章

强制TextBlock包装在WPF ListBox中

提问于
浏览
90

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

我用Google搜索并找到了类似问题的解决方案,但都没有奏效 .

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

3 回答

  • 1

    可以使用属性 TextWrapping 包装 TextBlock 的内容 . 而不是 StackPanel ,使用 DockPanel / Grid . 还有一件事 - 为 ListBox 设置 ScrollViewer.HorizontalScrollBarVisibility 属性为 Disabled 值 .

    根据马特的评论,将 Hidden 更新为 Disabled . 谢谢马特 .

  • 9

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

    为了动态更改它,它意味着不是修复值,但您需要将其绑定到可视树中的正确父元素 . 你可以这样:

    <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中的Live Visual Tree找到正确的元素(必须绑定到哪些元素) .

  • 125

    问题可能不在ListBox中 . 如果其中一个父控件提供了足够的空间,TextBlock将不会换行,因此它不需要换行 . 这可能是由ScrollViewer控件引起的 .

相关问题