John Steed
John Steed

Reputation: 629

Append New Paragraph To RichTextBox

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:

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

Upvotes: 4

Views: 9917

Answers (1)

denys-vega
denys-vega

Reputation: 3697

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.

Upvotes: 11

Related Questions