[wpf] TextBlock이 WPF ListBox에서 래핑하도록 강제

메시지를 표시하는 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>



답변

의 내용은 TextBlockproperty를 사용하여 래핑 할 수 있습니다 TextWrapping. 대신 /를 StackPanel사용하십시오 . 한 가지 더 – 세트 에 특성 가치 .DockPanelGridScrollViewer.HorizontalScrollBarVisibilityDisabledListBox

Matt의 의견 HiddenDisabled기반으로 업데이트 되었습니다 . 고마워 Matt.


답변

문제가 ListBox에 없을 수 있습니다. 부모 컨트롤 중 하나가 충분한 공간을 제공하여 래핑 할 필요가없는 경우 TextBlock은 래핑되지 않습니다. ScrollViewer 컨트롤로 인해 발생할 수 있습니다.


답변

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 의 라이브 비주얼 트리 를 사용 하여 적절한 요소 (무엇에 바인딩되어야 함)를 찾으십시오 .


답변