将新段落追加到RichTextBox [英] Append New Paragraph To RichTextBox

查看:80
本文介绍了将新段落追加到RichTextBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式向RichTextBox控件添加一个新段落(就像按Enter键一样).使用下面的代码,它确实添加了一个新段落,但是:

I need to programmatically add a new paragraph to a RichTextBox control (just like pressing 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, i.e. 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;

我正在测试一些东西-我注释掉了第二行和第三行代码,因此我仅阅读文档,然后立即将其重新设置为RichTextBox,但是这也删除了所有现有文本,因此可能出现此问题与此有关,但我无法弄清楚.

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.

我该如何克服这些问题,并以编程方式附加一个新段落,然后设置其焦点.

How can I overcome these issues and programmatically append a new paragraph, and then set its focus.

谢谢

推荐答案

部分视图:

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

以及背后的代码:

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();
}

希望对您有帮助.

这篇关于将新段落追加到RichTextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆