Monday, 21 November 2011

How to assign a dynamic resource link programmatically

Normally you assign resources in XAML by using the StaticResource or DynamicResource extension. But how to do it programmatically?
The static behavior is simple. Just find the resource by using the TryFindResource() method and set it to the property of your choice. But if you want to have it dynamically updated, the following code snipped is your solutions:

 
frameworkElement.SetResourceReference(dependencyProperty, resourceKey);
 

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