Search code examples
c#.netwpfrichtextboxrtf

Why doesn't my WPF RichTextBox keep the Superscript and Subscript data after saving and loading it again?


I'm kinda new here so I apologize in advance in case I'm not asking this question properly.

Currently, I'm working on a small TextEditor project in WPF, C# and .Net 4.5, but I recently found an issue that I can't seem to overcome. For some reason, the RichTextBox that gets converted to Rtf for saving proposes doesn't save the BaselineAlignmentProperty (superscripts & subscripts), which should be possible (according to the Rtf 1.5 spec: http://www.biblioscape.com/rtf15_spec.htm subscripting & superscripting are supported (\sub ; \super & \nosupersub)).

Code I'm using to convert the RichTextBox to Rtf and to load the Rtf to a RichTextBox (Storing data of rich text box to database with formatting):

    public static string ToRtf(RichTextBox RichText)
    {
        string RtfText;
        TextRange Text = new TextRange(RichText.Document.ContentStart, RichText.Document.ContentEnd);
        using (MemoryStream MS = new MemoryStream())
        {
            Text.Save(MS, DataFormats.Rtf);
            RtfText = Encoding.ASCII.GetString(MS.ToArray());
        }

        return RtfText;
    }

    public static void LoadRtfData(RichTextBox TextBox, string RtfText)
    {
        byte[] Data = Encoding.ASCII.GetBytes(RtfText);

        using (MemoryStream MS = new MemoryStream(Data))
        {
            TextRange Text = new TextRange(TextBox.Document.ContentStart, TextBox.Document.ContentEnd);
            Text.Load(MS, DataFormats.Rtf);
        }
    }

Also, changing the DataFormat to Xaml or XamlPackage (as described here as a possibility: http://umaranis.com/2010/11/29/save-and-load-richtextbox-content-in-wpf/) results in a crash.

Code I'm using to change the BaselineAligmentProperty on the selected text at MyTextBox:

MyTextBox.Selection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Bottom/*BaselineAligment.Subscript doesn't work either*/);

What should I do to make my RichTextBox Rtf include the BaselineAlignment data when saving/loading?


Solution

  • Managed to make it work by changing the DataFormat to Xaml.