简体   繁体   English

将新段落附加到RichTextBox

[英]Append New Paragraph To RichTextBox

I need to programmatically add a new paragraph to a RichTextBox control (just like pressing Enter). 我需要以编程方式将新段落添加到RichTextBox控件(就像按Enter键)。 Using the code below, it does add a new paragraph but: 使用下面的代码,它确实添加了一个新段落,但是:

  • It deletes all the existing text in the control 它删除控件中的所有现有文本
  • The insertion point remains in the first line and doesn't move to the second newly created line 插入点保留在第一行,不会移动到第二个新创建的行
  • It only seems to add a new paragraph once, ie if I run the code a second time, a third paragraph isn't created 它似乎只添加一个新段落,即如果我第二次运行代码,则不会创建第三段

      FlowDocument flowDoc= rtbTextContainer.Document; Paragraph pr = new Paragraph(); flowDoc.Blocks.Add(pr); rtbTextContainer.Document = flowDoc; 

I was testing a few things - I commented out the second and third lines of code, so I was only reading the Document and immediately set it back to the RichTextBox again, but that also deleted all existing text, so the issue might have something to do with that, but I can't figure it out. 我正在测试一些东西 - 我注释掉了第二行和第三行代码,因此我只是阅读了Document并立即将其重新设置回RichTextBox,但这也删除了所有现有文本,因此问题可能有些问题。这样做,但我无法理解。

How can I overcome these issues and programmatically append a new paragraph, and then set its focus. 我如何克服这些问题并以编程方式附加一个新段落,然后设置其焦点。

Thanks 谢谢

Part of the view: 部分观点:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <RichTextBox x:Name="RichTextBox1"/>
    <Button Grid.Row="1" Content="click-me" Click="Button_Click"/>
</Grid>

And the code behind: 而背后的代码:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var paragraph = new Paragraph();
    paragraph.Inlines.Add(new Run(string.Format("Paragraph Sample {0}", Environment.TickCount)));
    RichTextBox1.Document.Blocks.Add(paragraph);

    RichTextBox1.Focus();
    RichTextBox1.ScrollToEnd();
}

I hope it helps. 我希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM