Dynamic Loading of XAML in WinRt with Custom Types

Tags: WinRt Xaml

In my previous post I showed how you can dynamically load a XAML document at runtime and how to add it to the user interface. This works fine as long as you use only WinRt XAML types in your XAML document. As soon as you use a custom type in your XAML document, you will get an exception at XamlReader.Load that it can not find some types.

To look up types, WinRt is using the interface IXamlMetadataPorvider. In a .NET Metro Style App the App class is the implementation of this interface, but you will not see the implementation in the App.xaml.cs file. All the magic implementation stuff and plumbing code is done automatically by the designer. You can find it in the XamlTypeInfo.g.cs file which is located in the obj directory.

The reasons why WinRt is looking up types in that way are the following: The first is, WinRt is implemented in native code and therefore reflection is not available. The second is, a dynamic lookup of types at runtime is a expensive operation and costs a lot of execution time. If you declare all required information at desing time you can save resources at runtime. Saving resources at runtime was one design goal of Microsoft when they created WinRt. You can find more backgroud information to this in this blog post by Jérôme Laban.

This means, as soon as you would do some very dynamic stuff at runtime, like loading some XAML documents from disk or an online resource and you are using custom types in this documents, you have to provide type information of your custom types to the runtime. To do this you have two options:

  1. Use all of your custom types somewhere else in your application where you have designer support. In that case the type information will be generated by the desinger in the XamlTypeInfo.g.cs file. 
  2. Provide a custom implementation of the IXamlMetadataProvider.

The first option is very simple. For the second you have again differnt options you can choose from. One ist to implement the interface using reflection. But then you are doing what Microsoft is trying to avoid. Another option is to develop a mechanism to provide type information and read and write to this types without using reflection. I think the latter option is the better one because it is consistend with the desing goals of WinRt.

I developed an implementation of IXamlMetadataProvider in combination with a view model base class. You can read more about my solution in my next blog post.

No Comments

Add a Comment