问题
I made two richtexbox, one small richtexbox nested in a big richtextbox by using BlockUIContainer, see XAML file below.
<RichTextBox IsDocumentEnabled="True" x:Name="first" HorizontalAlignment="Left" Height="174" Margin="120,136,0,0" VerticalAlignment="Top" Width="254" TextChanged="first_TextChanged" MouseDoubleClick="first_MouseDoubleClick">
<FlowDocument>
<Paragraph>
<Run Text="RichTextBox"/>
</Paragraph>
<BlockUIContainer>
<RichTextBox IsReadOnly="True" x:Name="second" MouseDoubleClick="second_MouseDoubleClick" Width="239" TextChanged="second_TextChanged">
<FlowDocument>
<Paragraph>
<Run Text="RichTextBox1"/>
<Run Language="en" Text="hh"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</BlockUIContainer>
</FlowDocument>
</RichTextBox>
I want contents of both richtexbox saved in a RTF file. Normally we can use TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd), since now we have nested richtexbox, so i think TextRange is probablly not working. And maybe i will add some images in the richtextbox, so I want to try binary stream, see below. "first" is the name of big richtextbox. THE PATH is the path for RTF file.
FlowDocument document = first.Document;
System.IO.Stream ms = new System.IO.MemoryStream();
System.Windows.Markup.XamlWriter.Save(document, ms);
byte[] data = new byte[ms.Length];
ms.Position = 0;
ms.Read(data, 0, data.Length);
ms.Close();
File.WriteAllBytes(THE PATH, data);
But in the saved RTF file, when i open it, it shows like this,
<FlowDocument PagePadding="5,0,5,0" AllowDrop="True" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Paragraph>RichTextBox</Paragraph><Paragraph><Run xml:lang="en">test test test!!!</Run></Paragraph><BlockUIContainer><RichTextBox IsReadOnly="True" Name="second" Width="239"><FlowDocument PagePadding="5,0,5,0" AllowDrop="True"><Paragraph>RichTextBox1<Run xml:space="preserve"> </Run><Run xml:lang="en">hhthis is a small richtextbox</Run></Paragraph><Paragraph><Run xml:lang="en" xml:space="preserve" /></Paragraph></FlowDocument></RichTextBox></BlockUIContainer></FlowDocument>
I don´t want to see XAML plain text in the saved file, I want it to show like a normal word document, see below. and probably also see the border line of the small richtextbox (this border line doesnot show below)
RichTextBox
test test test!!!
RichTextBox1 hhthis is a small richtextbox
What should I do? or nested richtextbox by BlockUIContainer is not possible to show like this?
回答1:
You can do it by saving it and specifying the format. I omit the unnecessary code, but just replace memorystream with what you currently have.
richTextBox.SelectAll();
richTextBox.Selection.Save(new MemoryStream(), DataFormats.Rtf);
XamlWriter
will save it as a XAML format
来源:https://stackoverflow.com/questions/21922177/how-to-save-content-of-richtextbox-in-blockuicontainer-to-rtf-file