是否可以为RichTextBox中的预先创建的段落赋值

时间:2011-09-16 08:27:53

标签: c# wpf xaml richtextbox paragraph

考虑以下 XAML 代码:

<RichTextBox Name="dataRichTextBox" VerticalScrollBarVisibility="Auto" >
    <FlowDocument Name="dataFlowDocument" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Paragraph Name="dataParagraph">

        </Paragraph>
    </FlowDocument>
</RichTextBox>

我想要做的是,按照 XAML 中的定义,直接将Paragraph(以编程方式创建)分配给dataParagraph

代码看起来像:

Paragraph paraOne = new Paragraph();
Run run1 = new Run("I am run one"+Environment.NewLine);
// run1.Background = Brushes.Green;
paraOne.Inlines.Add(run1);
dataParagraph = paraOne; // expect that it will show up on the RichTextBox.

我试过了,但它不起作用。我到目前为止所阅读的示例似乎都是以编程方式创建FlowDocumentParagraph,然后将Runs'分配给它们。是否有可能以我实施的方式实现它。

1 个答案:

答案 0 :(得分:1)

您无法将XAML中声明的段落替换为新段落,但您可以直接使用它。

保持您的XAML原样,将您的代码更改为此,它将起作用:

dataParagraph.Inlines.Add(new Run("I am run one" + Environment.NewLine));

或者,只需将新段落添加到FlowDocument,而不是尝试将其分配给现有段落。