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:
- Fully qualify all namespaces. It has problem finding local assemblies by namespace only.
- Consider using the ContentPropertyAttribute.
- Useful notes on XAML 2009: http://wpftutorial.net/XAML2009.html