我如何将段落数据绑定到TextBlock?

问题描述:

如何使用 Paragraph 对象并将其数据绑定到TextBlock以用于DataTemplate?
一个简单的绑定什么都不做,只是Paragraph对象的 ToString()

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.

InLines属性将让我添加一个手动组成Paragraph的TextRun的列表,但这不能绑定到,我可以用一个基于绑定的解决方案来实现。

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.

这是一个使用嵌套的例子物品控制。不幸的是,它会使一个TextBlock每个Inline而不是将整个段落放入一个TextBlock:

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>

如果您想要每个元素一个Paragraph,您应该按照建议使用一个Paragraph,并使用只读RichTextBox,或做这个人从TextBlock 导出,以便Inlines属性可以绑定。

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.