0

I'm saving a resource dictionary to Xaml using XamlWriter and I noticed that for string properties with just {p}, the XamlWriter adds a {} before the text (resulting in {}{p}).

Why does that happen? Is there any way to prevent this? Or at least to remove it safely when read back using a standard XDocument.Parse()?

Here's how I'm saving it:

public class Example 
{
    public string Property { get; set; }
}

var resource = new ResourceDictionary();
resource.Add("Example", new Example { Property = "{p}" });

var settings = new XmlWriterSettings
{
    Indent = true,
    IndentChars = "\t",
    OmitXmlDeclaration = true,
    CheckCharacters = true,
    CloseOutput = true,
    ConformanceLevel = ConformanceLevel.Fragment,
    Encoding = Encoding.UTF8,
};

using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = XmlWriter.Create(fileStream, settings))
    XamlWriter.Save(resource, writer);

Edit

The {} is a scape sequence that is added when the text contains an open and close brackets like {...}.

https://learn.microsoft.com/en-us/dotnet/desktop/xaml-services/escape-sequence-markup-extension

Now, the only question remaining is how can I safely remove these scape sequences from my text. Can I simply do a replace or trim, or is there a method for that already?

Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79
  • It was not needed, the question was about the theory, but I already know why it's happening. I just wish to know if there's a simple and safe way to remove the scape sequences from the Xaml. – Nicke Manarin Apr 19 '21 at 03:32
  • The curly brackets are uses for binding. So removing the brackets the bindings will not work. – jdweng Apr 19 '21 at 08:14

1 Answers1

0

The curly braces are added to escape braces in the values being serialized. You shouldn't really remove them.

or is there a method for that already?

No, there isn't. If you want to modify the written text, you are on your own. Using string.Replace or similar would be sufficient. There is no better built-in way.

mm8
  • 163,881
  • 10
  • 57
  • 88