开发者

How do I parse a non-GUI XAML file?

开发者 https://www.devze.com 2023-03-22 06:01 出处:网络
Ok, so here\'s what I want to do. Create a \"configuration file\" using XAML 2009. It would look something like this:

Ok, so here's what I want to do.

  1. Create a "configuration file" using XAML 2009. It would look something like this:

    <TM:Configuration 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:tm="clr-namespace:Test.Monkey;assembly=Test.Monkey" 
    >
        <TM:Con开发者_开发问答figuration.TargetFile>xxxx</TM:Configuration.TargetFile>
    <TM:Configuration 
    
  2. Parse this file at runtime in order to get the object-graph.


Easy way:

var z = System.Windows.Markup.XamlReader.Parse(File.ReadAllText("XAMLFile1.xaml"));

(Turns out this does support XAML 2009 after all.)

Hard way, but with less dependencies:

var x = ParseXaml(File.ReadAllText("XAMLFile1.xaml"));

    public static object ParseXaml(string xamlString)
    {
        var reader = new XamlXmlReader(XmlReader.Create(new StringReader(xamlString)));
        var writer = new XamlObjectWriter(reader.SchemaContext);
        while (reader.Read())
        {
            writer.WriteNode(reader);
        }
        return writer.Result;
    }

Creating XAML from object graph:

    public static string CreateXaml(object source)
    {
        var reader = new XamlObjectReader(source);
        var xamlString = new StringWriter();
        var writer = new XamlXmlWriter(xamlString, reader.SchemaContext);
        while (reader.Read())
        {
            writer.WriteNode(reader);
        }
        writer.Close();
        return xamlString.ToString();
    }

Notes:

  1. Fully qualify all namespaces. It has problem finding local assemblies by namespace only.
  2. Consider using the ContentPropertyAttribute.
  3. Useful notes on XAML 2009: http://wpftutorial.net/XAML2009.html
0

精彩评论

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