user10690106
user10690106

Reputation:

Clone all texts from RichTextBox1 to RichTextBox2 by keeping text format

This is my xaml file.

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <RichTextBox x:Name="RichTextBox1" Height="150" VerticalAlignment="Top" Background="Yellow">
        <FlowDocument x:Name="FlowDocument1">
            <Paragraph>
                <Run Text="Lorem Ipsum is simply"/>
                <Run FontWeight="Bold" Text="dummy text"/>
                <Run FontStyle="Italic" Text="of the printing and typesetting industry."/>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
    <RichTextBox x:Name="RichTextBox2" Height="150" VerticalAlignment="Bottom" Background="Pink">
        <FlowDocument x:Name="FlowDocument2">
            <Paragraph>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
</Grid>
</Window>

I want to clone all texts from RichTextBox1 to RichTextBox2 by keeping text format.

So, bold text and italic text must be clone with their formatting.

I need code behind solution. (C# or vb.net)

Please note that following link explains how to save RichTextBox to xaml file and load from xaml file to RichTextBox. But I dont want a solution like that. I dont want to use external file.

https://learn.microsoft.com/tr-tr/dotnet/framework/wpf/controls/how-to-save-load-and-print-richtextbox-content

Upvotes: 1

Views: 168

Answers (1)

Alexander
Alexander

Reputation: 9632

According to the docs you can save RichTextBox content into a stream. So it is possible to use MemoryStream without external file

using (var contentStream = new MemoryStream())
{
    TextRange range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);
    range.Save(contentStream, DataFormats.XamlPackage);

    //rewind stream
    contentStream.Position = 0;

    TextRange range2 = new TextRange(RichTextBox2.Document.ContentStart, RichTextBox2.Document.ContentEnd);
    range2.Load(contentStream, DataFormats.XamlPackage);
}

Upvotes: 1

Related Questions