Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set image source in code behind

There are numerous questions and answers regarding setting image source in code behind, such as this Setting WPF image source in code.

I have followed all these steps and yet not able to set an image. I code in WPF C# in VS2010. I have all my image files under a folder named "Images" and all the image files are set to Copy always. And Build Action is set to Resource, as instructed from documentation.

My code is as follow. I set a dog.png in XAML and change it to cat.png in code behind.

// my XAML
<Image x:Name="imgAnimal" Source="Images/dog.png" />

// my C#
BitmapImage img = new BitmapImage();
img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png");
imgAnimal.Source = img;

Then I get a empty, blank image of emptiness. I do not understand why .NET makes setting an image so complicated..w

[EDIT]

So the following works

imgAnimal.Source = new BitmapImage(new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png"));

It works, but I do not see any difference between the two code. Why the earlier doesn't work and the latter does? To me they are the same..

like image 603
KMC Avatar asked Mar 16 '12 08:03

KMC


1 Answers

Try following:

imgAnimal.Source = new BitmapImage(new Uri("/FooApplication;component/Images/cat.png", UriKind.Relative));

Default UriKind is Absolute, you should rather use Relative one.

[EDIT]

Use BeginInit and EndInit:

BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png");
img.EndInit();
imgAnimal.Source = img;
like image 189
Marcin Avatar answered Oct 02 '22 01:10

Marcin