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 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With