Becky Green
Becky Green

Reputation: 645

WPF Dynamic Image Loading into ResourceDictionary programmatically

Morning folks,

I've been trying to cut out some of my app's processing when I stumbled upon a suggestion on SO to load all images into a resource dictionary via BitmapImages, then referencing them rather than loading an image each time. My problem is that I need to do this all programmatically, so:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />

has become:

BitmapImage bI = new BitmapImage();
Uri imgUri = new Uri(fI.FullName, UriKind.RelativeOrAbsolute);
bI.UriSource = imgUri;
DataTemplateKey dTK = new DataTemplateKey(typeof(BitmapImage));
imageDictionary.Add(dTK, bI);

Which I think should work, but as it loops due to the images loading based on database content, I immediatly get a key already added error on the second loop-through. Is there any way to create a datatemplatekey that I can name myself rather than have it based on the type?

Thanks, Becky

Upvotes: 1

Views: 1333

Answers (1)

Wouter Janssens
Wouter Janssens

Reputation: 1613

It is not possible to add a key to the datatemplate but maybe you fix your problem by creating a DataTemplateSelector. On the link below you can find very good information on how to do that:

http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselector

Upvotes: 1

Related Questions