简体   繁体   中英

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM