How to change an image in WPF at runtime in C#

I was doing some code that checks the number of network round trips to the database within a single transaction. I was coding it using WPF in C#. What I wanted to do was set the image in the Status Bar to a green image if the transaction took 1 trip, a yellow image if it took 2 trips and a red image if it was greater than 2 trips to the database.

Initially I thought I could just set ImageName.Source to the image file. However, when you create an image in a .XAML file and Image is of type System.Windows.Media and you can not simply pass a string to it. Instead I needed to reference all my images from within the Windows.Resources tags of the .XAML file. Not so complex, see the code below:

< Window x:Class="XXX"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
  < Window.Resources >
   < ResourceDictionary >
    < ImageSource x:Key="ImageGreen">Images/greenLight.png / > 
    < ImageSource x:Key="ImageYellow">Images/yellowLight.png / >
    < ImageSource x:Key="ImageRed">Images/redLight.png / >
   < /ResourceDictionary > 
  < /Window.Resources >
  < Grid>
   < Image Name="ImageStatus" Source="/Images/greenLight.png" / >
  < /Grid >
< /Window >

Notice above that I have 3 ImageSource references (ImageGreen, ImageYellow and ImageRed) and an Image named ImageStatus. I need this reference so that I can access them from my code-behind. In the code-behind, I simply add this line of C# code:

ImageStatus.Source = (ImageSource)FindResource("ImageRed");

This code makes the reference to the source of my Image, ImageStatus, searches for the ImageSource, ImageRed and set the 2 equal. You can place whatever logic around the setting of the ImageStatus source based on your requirements.




Leave a Comment

Your email address will not be published.