How to set Image Source in C# to XAML Static Resource programmatically?

Danny Beckett picture Danny Beckett · Sep 5, 2013 · Viewed 69.8k times · Source

I have this ResourceDictionary in Main.xaml:

<Window.Resources>
    <ResourceDictionary>
        <BitmapImage x:Key="Customer" UriSource="Icons/customer.png"/>
        <BitmapImage x:Key="Project" UriSource="Icons/project.png"/>
        <BitmapImage x:Key="Task" UriSource="Icons/task.png"/>
    </ResourceDictionary>
</Window.Resources>

I initially set the image using:

<Image Name="TypeIcon" HorizontalAlignment="Left" VerticalAlignment="Center"
    Source="{StaticResource Customer}" Height="16" Width="16"/>

I'm trying to change TypeIcon's Source from Customer to Project in a C# method.

I've tried using:

TypeIcon.Source = "{StaticResource Project}";

But I get this error:

Cannot implicitly convert type string to System.Windows.Media.ImageSource

I've tried defining the image using new ImageSource(), but this doesn't work either.

How can I change the image's Source programmatically in C#?

Answer

Danny Beckett picture Danny Beckett · Sep 5, 2013

After much Googling, whilst writing this question, I figured out how to do it:

TypeIcon.Source = (ImageSource) Resources["Project"];