Search code examples
wpfdata-bindingxamltextblockparagraph

How would I databind a Paragraph to a TextBlock?


How would I take a Paragraph object and databind them to the TextBlock for use in a DataTemplate? A plain bind does nothing, just a ToString() of the Paragraph object.

The InLines property would let me add a list of TextRun's that make up the Paragraph manually, but that can't be bound to and I could really do with a binding based solution.

Edited question to focus on what I really need to do.


Solution

  • Here's an example using a nested ItemsControl. Unfortunately, it will make one TextBlock per Inline instead of putting the whole Paragraph into one TextBlock:

    <Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:sys="clr-namespace:System;assembly=mscorlib"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Grid.Resources>
            <FlowDocument x:Key="document">
                <Paragraph><Run xml:space="preserve">This is the first paragraph.  </Run><Run>The quick brown fox jumps over the lazy dog.</Run></Paragraph>
                <Paragraph><Run xml:space="preserve">This is the second paragraph.  </Run><Run>Two driven jocks help fax my big quiz.</Run></Paragraph>
                <Paragraph><Run xml:space="preserve">This is the third paragraph.  </Run><Run>Sphinx of black quartz, judge my vow!</Run></Paragraph>
            </FlowDocument>
            <DataTemplate DataType="{x:Type Paragraph}">
                <ItemsControl ItemsSource="{Binding Inlines}" IsHitTestVisible="False">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
            </DataTemplate>
        </Grid.Resources>
        <ListBox ItemsSource="{Binding Blocks, Source={StaticResource document}}"/>
    </Grid>
    

    If you want one Paragraph per element you should probably do as suggested and use a read-only RichTextBox, or do what this person did and derive from TextBlock so that the Inlines property can be bound.