3

so in WPF i've created a RichTextBox and implemented the functionality to be able to format selected text (bold, undelined, font, etc...), but now i would like to export all of the formatting to a XML file, so when i would load it the loaded file would give me the same text with the same formatting. I think that the best way to do this would be, if i could find each place where there is formatting in the RTB and then save it as a text range, but i dont know if RTB has a method for finding if a part of text is formatted.

Here is what i've got: xaml:

<Button Name = "export" Click = "export_Click"/>
<RichTextBox x:Name="RTB"/>

and the c#:

private void export_Click(object sender, RoutedEventArgs e){
    TextRange range = new TextRange();
    //here is where i want to access the formatted areas
    //something like: range = RTB.document.getBoldArea();
    //and then i could export what i got in the text range to a xml file
}

thanks in advance to anyone willing to help!

1 Answer 1

4

You can actually access XAML content directly, which is itself obviously XML. You could either save this directly or manipulate/translate it into your own schema.

To get the XAML for a RichTextBox :

static string GetXaml(RichTextBox rt)
{
    TextRange range = new TextRange(rt.Document.ContentStart, rt.Document.ContentEnd);
    MemoryStream stream = new MemoryStream();
    range.Save(stream, DataFormats.Xaml);
    string xamlText = Encoding.UTF8.GetString(stream.ToArray());
    return xamlText;
}

To set the XAML content for a RichTextBox :

static void SetXaml(RichTextBox rt, string xamlString)
{
    StringReader stringReader = new StringReader(xamlString);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    Section sec = XamlReader.Load(xmlReader) as Section;
    FlowDocument doc = new FlowDocument();
    while (sec.Blocks.Count > 0)
        doc.Blocks.Add(sec.Blocks.FirstBlock);
    rt.Document = doc;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.