views:

4616

answers:

1

I would like to know exactly how to dynamically use a Dictionary Resource in the C# code behind - ie.. I would like to load images at runtime from an image resource within a dictionary

I have a program that has 3 images in a WPF Dictionary - these are images set as image resources.

Then in the code behind of my WPF Window I want to load any one of the three images based on user initiated events.

There is no real code I have to show as nothing that I have done works.

Ideas?

+11  A: 

First, make sure you've defined your image resources like this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
    <ImageSource x:Key="image1">images/image1.jpg</ImageSource>
    <ImageSource x:Key="image2">images/image2.jpg</ImageSource>
</ResourceDictionary>

Secondly, I'm assuming that your WPF dictionary is in its own file. Now you have to make sure you've merged your dictionary into your main window's XAML (skip this step if your resource dictionary is defined inside of the window's XAML). In your window's XAML file, make sure you have something like this:

<Window.Resources>
 <ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
   <ResourceDictionary Source="myDictionary.xaml" />
  </ResourceDictionary.MergedDictionaries>
 </ResourceDictionary>
</Window.Resources>

Now, in your code-behind, you can use the FindResource() method to locate your image resource by it's key name (the value of the x:Key attribute on the ImageSource in the resource dictionary) like so:

imageControl.Source = (ImageSource)FindResource("image1");

Hope this helps!

Eric Smith
ah, what I was missing was the merging of my dictionary into the Window.Resources - much appreciated!
Tab
Nicely written response. +1 and thanks! Browsing MSDN is pain for such scenarios
Gishu