KMC
KMC

Reputation: 20046

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

Upvotes: 4

Views: 21431

Answers (1)

Marcin
Marcin

Reputation: 3262

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;

Upvotes: 12

Related Questions