How to read a WPF RichTextBox Content?

The following code creates a RichTextBox in WPF and adds a flow document to it. Code also adds a button in XAML.

<Window x:Class="RichTextBoxSample.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" Height="300" Width="300">

    <Grid>

        <RichTextBox Name="RTB" Height="167" Margin="0,0,0,95" Width="278">

            <FlowDocument>

                <Paragraph>

                    <Run>First paragraph goes here. Type some text here.</Run>

                </Paragraph>

                <Paragraph>

                    <Run>Second paragraph goes here. Type some text here.</Run>

                </Paragraph>         

            </FlowDocument>

        </RichTextBox>

        <Button Height="36" Margin="12,0,0,34" Name="button1" VerticalAlignment="Bottom"

                HorizontalAlignment="Left" Width="97" Click="button1_Click">Get Contents</Button>

    </Grid>

</Window>



On button click event handler, which looks like following, we are going to read contents of a RichTextBox. As you can see from the code below, we use RichTextBox.ContentStart and RichTextBox.ContentEnd to get the entire content and later display in a MessageBox.

private void button1_Click(object sender, RoutedEventArgs e)

{

    TextRange textRange = new TextRange(RTB.Document.ContentStart,

        RTB.Document.ContentEnd  );

    MessageBox.Show(textRange.Text);

}