Search code examples
c#wpfrichtextboxdependency-propertiesflowdocument

How to store style information lastingly in a FlowDocument paragraph?


My text application is hosting a FlowDocument in a WPF RichTextBox. You can give each paragraph its own style (FrameworkContentElement.Style). A text description of the style refering to the current paragraph (at caret position) is shown in a ComboBox. After storing and reloading a document I notice: style of each paragraph is null. So I need a way to store style info [as int or string value] in a paragraph. I tried to abuse NameProperty, ToolTipProperty and TagProperty, but they resist.

Has someone an idea? I'd appreciate that.

I know, abusing WPF properties is no professional approach, there may be a fundamental other solution.

All style properties are implemented as dynamic resources and can be changed by the user. If, let's say a background color of a paragraph style is changed, all paragraphs using this style should change their backcolor immediately.


Solution

  • Styles will be embedded and reloaded if you store and load like this:

    // Storing a FlowDocument
    using (FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
    {
        XamlWriter.Save(_flowDoc, fs);
    }
    
    // Loading a FlowDocument into a RichTextBox
    using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read))
    {
        _flowDoc = (FlowDocument)XamlReader.Load(fs);
        _rtb.Document = _flowDoc;
    }