Append New Paragraph To RichTextBox

徘徊边缘 提交于 2019-12-23 19:10:13

问题


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;
    

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.

Thanks


回答1:


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.



来源:https://stackoverflow.com/questions/28640039/append-new-paragraph-to-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!