views:

595

answers:

2

I know this is an easy question but I can't figure it out or find the answer anywhere. I'm just trying to change the image source during runtime in WPF using C#. Whenever the code runs, it just removes 1.gif and has a blank white box, instead of displaying 2.gif. Thanks in advance.

XAML:

<Image x:Name="img" Height="150" Margin="142,20,138,0" VerticalAlignment="Top">
        <Image.Source>
            <BitmapImage UriSource="C:\Users\John\1.gif" />
        </Image.Source>
</Image>

C#:

string sUri = @"C:\Users\John\2.gif";
Uri src = new Uri(sUri, UriKind.RelativeOrAbsolute);
BitmapImage bmp = new BitmapImage(src);
img.Source = bmp;
A: 

Obvious questions first: you're sure that the image 2.gif really exists, and that the BitmapImage isn't null when you set it as the source of img?

A: 

You need to initialize the BitmapImage. The correct code would be something like:

BitmapImage bmp = new BitmapImage(src);
bmp.BeginInit();
bmp.EndInit();

That should get you your image.

Kiranu