Wrap text with indent in WPF textBlock

6.9k views Asked by At

I am using a listbox to display undo redo list with data template as:

<ListBox x:Name="actionList"
           Height="150"
           HorizontalAlignment="Stretch"
           VerticalAlignment="Stretch"
           MouseMove="ListBoxMouseMove"
           ScrollViewer.VerticalScrollBarVisibility="Visible"
           SelectionMode="Extended"
           Style="{StaticResource CustomListBoxStyle}">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <TextBlock Width="235"
                   HorizontalAlignment="Stretch"
                   VerticalAlignment="Stretch"
                   FontSize="11"
                   Text="{Binding DisplayText}"
                   TextWrapping="Wrap" />
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>

It is working as expected, but for long undo redo string the wrapping occurs but it is aligned to first chracter of the line. we want it to indent a bit to clearly identify the two list items. Illustrated as follows:

Word wrap desired functionality

How can we achieve the same.

1

There are 1 answers

4
almulo On

They "easier" way to do this would probably involve using a Paragraph object to represent the text.

Paragraphs natively support indentation with properties like TextIndent (controls first line indentation, and you can set it to a negative value) or Margin (sets a margin for the whole paragraph, but respects the first line indentation).

<ListBox.ItemTemplate>
    <DataTemplate>
        // IsHitTestVisible is set to false to avoid FlowDocument's built-in text selection
        //     from disrupting the regular ListBox mouse selection behavior
        <Grid IsHitTestVisible="False">
            <FlowDocumentScrollViewer ScrollViewer.VerticalScrollBarVisibility="Disabled"
                                      ScrollViewer.HorizontalScrollBarVisibility="Disabled">
                 <FlowDocument FontSize="12"
                               FontFamily="Calibri" 
                               Foreground="Black" 
                               PagePadding="0">
                     <Paragraph TextIndent="-10" 
                                Margin="10,0,0,0">
                         <Run Text="{Binding ., Mode=OneWay}" />
                     </Paragraph>
                 </FlowDocument>
            </FlowDocumentScrollViewer>
        </Grid>
    </DataTemplate>
</ListBox.ItemTemplate>