Search code examples
wpf.net-3.5imagesource

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;

Solution

  • 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.