WP7 TextBlock inside a ListBox not wrapping text

2019-04-08 21:05发布

问题:

I have a ListBox which has StackPanels holding a TextBlock and an Image horizontally, followed by a ContentPresenter. This is what the XAML looks like:

<Grid x:Name="ContentPanel"
      Grid.Row="1"
      Margin="12,0,12,0">
  <ListBox x:Name="MainListBox"
           Margin="12,0,12,0"
           SelectionChanged="MainListBox_SelectionChanged">
    <ListBox.ItemTemplate>
      <DataTemplate>

        <StackPanel>
          <toolkit:ContextMenuService.ContextMenu>
            <toolkit:ContextMenu x:Name="ContextMenu"
                                 Opened="ContextMenu_Opened">
              <toolkit:MenuItem Header="edit"
                                Tag="edit"
                                Click="MenuItem_Click" />
              <toolkit:MenuItem Header="delete"
                                Tag="delete"
                                Click="MenuItem_Click" />
            </toolkit:ContextMenu>
          </toolkit:ContextMenuService.ContextMenu>
          <StackPanel Orientation="Horizontal"
                      HorizontalAlignment="Left">

            <!-- **** This text won't wrap **** -->
            <TextBlock Text="{Binding Header}"
                       TextWrapping="Wrap"
                       Style="{StaticResource PhoneTextNormalStyle}"
                       Foreground="{StaticResource PhoneAccentBrush}" />

            <Image Source="/image.png"
                   Visibility="{Binding ImageVisibility}" />

          </StackPanel>

          <ContentPresenter Content="{Binding Content}"
                            HorizontalAlignment="Stretch" />

        </StackPanel>

      </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment"
                Value="Stretch" />
      </Style>
    </ListBox.ItemContainerStyle>
  </ListBox>
</Grid>

I'm setting the ItemsSource of the ListBox to an ObservableCollection within the page constructor. Everything works fine until the Header text becomes too long, in which case it is not wrapping as I've specified it to. How can I force the TextBlock to wrap the text?

Thanks for your help!

回答1:

This is likely a result of not restricting the width of the TextBlock, so it is growing horizontaly off screen where you can't see it.