wpfwpf-4.0

ScrollViewer and TextBlock wrapping


I have the following layout (simplified):

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition MaxWidth="400" />
    <ColumnDefinition />
  </Grid.ColumnDefinitions>

  <!-- Code for Column=0 -->

  <ScrollViewer Grid.Column="1">
    <Grid x:Name="layoutGrid">

      <Grid.ColumnDefinitions>
        <Grid.ColumnDefinition Width="Auto" />
        <Grid.ColumnDefinition MinWidth="100" MaxWidth="400" />
        <Grid.ColumnDefinition Width="Auto" />
      </Grid.ColumnDefinitions>

      <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
      </Grid.RowDefinitions>


      <!-- Code for Row=0 and Row=1 -->

      <GroupBox Grid.ColumnSpan="3" Grid.Row=2>
        <TextBlock Text="{Binding ...}" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Top" />
      </GroupBox>
    </Grid>
  </ScrollViewer>
</Grid>

How can I achieve this in xaml? It seems that as soon as ScrollViewer is inserted, TextBlock does not wrap any more.


Solution

  • Just give the TextBlock a MaxWidth which is the ActualWidth of either the GroupBox or in your case even the layoutGrid (as your GroupBox has the same width). This would force the TextBlock to have to wrap when it's Width exceeds that dimension and thereby giving you your requirement.

    So something like:

    <GroupBox x:Name="grpBox"
              Grid.Row="2"
              Grid.ColumnSpan="3">
      <TextBlock MaxWidth="{Binding ElementName=grpBox,
                                    Path=ActualWidth}"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  Text="{Binding ...}"
                  TextWrapping="Wrap" />
    </GroupBox>
    

    or

    <TextBlock MaxWidth="{Binding ElementName=layoutGrid,
                                  Path=ActualWidth}"
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                Text="{Binding ...}"
                TextWrapping="Wrap" />