开发者

How do I parse a non-GUI XAML file?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜