4

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

1 Answer 1

12

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.