Forums - C# Corner

Forum guidelines

how do I render an image at run time in wpf

Dec 5 2012 3:21 PM
I'm just doing a basic practice project that envolves a street light and the light/image changes color at the push of a button. at design time I can see all three of my images clearly but at runtime none of them will show up. I searched the hell out of google and I followed about three different examples but nothing will work.

this is what I have in my xaml code so far

<Window x:Class="stopLightDemo.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="517" Margin="6,0,-6,0">
<Button x:Name="btnGreen" Content="Green" Margin="310,30,50,0" VerticalAlignment="Top" Height="24" Click="btnGreen_Click" />
<Button x:Name="btnYellow" Content="Yellow" Margin="310,71,50,0" VerticalAlignment="Top" Height="24" Click="btnYellow_Click"/>
<Button x:Name="btnRed" Content="Red" HorizontalAlignment="Left" Margin="310,112,0,0" VerticalAlignment="Top" Width="157" Height="24" Click="btnRed_Click"/>
<Button x:Name="btnClose" Content="Close" HorizontalAlignment="Left" Margin="310,256,0,0" VerticalAlignment="Top" Width="157" Height="29" Click="btnClose_Click" />

<Image HorizontalAlignment="Left" Height="299" Margin="25,10,0,0" VerticalAlignment="Top" Width="227" Source="images/Stop.png" Name="imgStop"/>
<Image HorizontalAlignment="Left" Height="299" Margin="25,10,0,0" VerticalAlignment="Top" Width="227" Source="images/Caution.png" Name="imgCaution"/>
// I tried somthing different here with the green light*********************************************************************
<Image HorizontalAlignment="Left" Height="299" Margin="25,10,0,0" VerticalAlignment="Top" Width="227">
<BitmapImage DecodePixelWidth="227" DecodePixelHeight="299" UriSource="images/Go.png"/>

now here's my C# code
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace stopLightDemo

public partial class MainWindow : Window

public MainWindow()

private void btnGreen_Click(object sender, RoutedEventArgs e)
Image myImage = new Image();
myImage.Width = 227;
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.UriSource = new Uri(@"G:\Users\Jason\Documents\C# Projects\WPF\stopLightDemo\stopLightDemo\images\Go.png");
myBitmapImage.DecodePixelWidth = 227;
myImage.Source = myBitmapImage;

private void btnYellow_Click(object sender, RoutedEventArgs e)


private void btnRed_Click(object sender, RoutedEventArgs e)


private void btnClose_Click(object sender, RoutedEventArgs e)


what could I be possibly be doing wrong????
Thank You!!!