开发者

WPF Richtextbox XamlWriter behaviour

开发者 https://www.devze.com 2022-12-26 19:09 出处:网络
I am trying to save some c# source code into the database. Basically I have a RichTextBox that users can type their code and save that to the database.

I am trying to save some c# source code into the database. Basically I have a RichTextBox that users can type their code and save that to the database.

When I copy and paste from the visual studio environment, I would like to preserve the formating etc. So I have chosen to save the FlowDocuments Xaml to the database and set this back to the RichTextBox.Document.

My below two function serialise and deserialise the RTB's contents.

     private string GetXaml(FlowDocument document)
    {
        if (document == null) return String.Empty;
        else{
            StringBuilder sb = new StringBuilder();
            XmlWriter xw = XmlWriter.Create(sb);
            XamlDesignerSerializationManager sm = new XamlDesignerSerializationManager(xw);
            sm.XamlWriterMode = XamlWriterMode.Expression;                

            XamlWriter.Save(document, sm );
            return sb.ToString();
        }
    }

    private FlowDocument GetFlowDocument(string xamlText)
    {
        var flowDocument = new FlowDocument();
        if (xamlText != null) flowDocument = (FlowDocument)XamlReader.Parse(xamlText);
        // Set return value
        return flowDocument;
    }

However when I try to serialise and deserialise the following code, I am noticing this incorrect(?) behaviour

using System;
public class TestCSScript : MarshalByRefObject
{

}

Serialised XAML is

using System; public class TestCSScript : 开发者_Go百科 MarshalByRefObject {}{ }

Notice the the new set of "{}"

What am I doing wrong here... Thanks in advance for the help!


I have resigned to a tardy solution for now, but if any of you finds a clean one, please post it.

I have used a Replace call of Stringbuilder to remove the undesired characters.

    private string GetXaml(FlowDocument document)
    {
        if (document == null) return String.Empty;
        else
        {

            StringBuilder sb = new StringBuilder();
            using (XmlWriter xw = XmlWriter.Create(sb))
            {
                XamlDesignerSerializationManager sm = new XamlDesignerSerializationManager(xw);
                sm.XamlWriterMode = XamlWriterMode.Expression;

                XamlWriter.Save(document, sm);
            }
            sb.Replace("{}", "");
            return sb.ToString();
        }

    }

I have a feeling that when the xamlwriter encounters "{" character - it intreprets that as a binding expression. I wonder what the escape sequence is for this character.

Note - I tried changing the

XamlWriterMode from XamlWriterMode.Expression to XamlWriterMode.Value

with no joy.

0

精彩评论

暂无评论...
验证码 换一张
取 消