如何解析非GUI XAML文件?

时间:2011-07-20 19:35:36

标签: xaml xaml-2009

好的,这就是我想做的事。

  1. 使用XAML 2009创建“配置文件”。它看起来像这样:

    <TM:Configuration 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:tm="clr-namespace:Test.Monkey;assembly=Test.Monkey" 
    >
        <TM:Configuration.TargetFile>xxxx</TM:Configuration.TargetFile>
    <TM:Configuration 
    
  2. 在运行时解析此文件以获取对象图。

1 个答案:

答案 0 :(得分:0)

简单方法:

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

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

很难,但依赖性较低:

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;
    }

从对象图创建XAML:

    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();
    }

注意:

  1. 完全限定所有名称空间。它仅通过命名空间查找本地程序集时遇到问题。
  2. 考虑使用ContentPropertyAttribute。
  3. 有关XAML 2009的有用说明:http://wpftutorial.net/XAML2009.html