Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Monday, July 23, 2012

How to load BAML resources

What is BAML?

WPF is based on XAML an XML dialect to describe object graphs. This is very powerful but parsing an XAML file at runtime is quite expensive. So the MarkupCompiler converts the XAML file to a more compact binary version called BAML. The BAML stream then is stored to the resources of the assembly and loaded within the InitializeComponent method.
The BAML API is something unique of WPF and was not public until .NET 4.0. Now it's available through the Baml2006Reader implementation. The following code shows how to load a BAML stream in .NET 3.5 and 4.0

Load an object from a BAML stream

Load a BAML stream in .NET 3.5 (by using reflection):
 
var pc = new ParserContext();
var readerType = presentationFrameworkAssembly
                  .GetType("System.Windows.Markup.XamlReader");
var method = readerType.GetMethod("LoadBaml", 
                  BindingFlags.NonPublic | BindingFlags.Static);
return method.Invoke(null, new object[] {stream, pc, null, false});
 
 
Load a BAML stream in .NET 4.0:
 
var reader = new Baml2006Reader(stream);
var writer = new XamlObjectWriter(reader.SchemaContext);
while(reader.Read())
{
    writer.WriteNode(reader);
}
return writer.Result;

No comments:

Post a Comment