views:

40

answers:

1

I'm looking for a way to bind xaml images dynamically in code.

There are lots of examples online to show how to bind png or xaml images in the window's xaml, or to load png files in code.

But I have found no examples for xaml files with build action=page. XmlReader can't handle them since they are compiled to baml.

LoadComponent(new Uri("...filename.baml") will apparently load the baml but what kind of image class do I load this into? BitmapImage(new Uri("...filename.baml") does not seem to work, probably because it's not a bitmap.

Thanks in advance.

A: 

After much trial and error and searching, the following article helped me on my way: http://stackoverflow.com/questions/2032294/access-resourcedictionary-items-programmatically

I didn't need the step of adding the ResourceDictionary to the merged dictionaries.

Step 1. Get the ResourceDictionary using the xaml filename:

ResourceDictionary rd = System.Windows.Application.LoadComponent(new Uri("/projectname;component/iconfolder/iconfilename.xaml", System.UriKind.Relative)) as ResourceDictionary;

Step 2. Get the xaml as a DrawingImage out the ResourceDictionary

return rd[rd.Keys.Cast().ToList()[0]] as DrawingImage;

So I can bind to the viewmodel property, which returns the iconfilename.xaml. Then I use a converter with the above code to lookup the icon and return it as a DrawingImage.

If you have a more elegant way of doing it, I'd be interested to see it.

Carl