jb.
jb.

Reputation: 10331

wpf change image source

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;

Upvotes: 1

Views: 4685

Answers (2)

Carlos G.
Carlos G.

Reputation: 4634

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.

Upvotes: 1

user112889
user112889

Reputation: 805

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?

Upvotes: 0

Related Questions