Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

wpf - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...