John
John

Reputation: 1477

Load Image at runtime from resource in WPF

Im trying to load a image at runtime in WPF using the following code

_image = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(@"pack://application:,,,/images/tagimages/placeholder.png", UriKind.Absolute);                
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
_image.Source = src;
_image.Stretch = Stretch.None;

In my project I have a folder called images and a sub folder of that folder called tagimages that contains the placeholder.png. When I run this code I get the following error

"Cannot locate resource 'images/tagimages/placeholder.png'"

What am I doing wrong?

Upvotes: 6

Views: 14816

Answers (2)

Epirocks
Epirocks

Reputation: 502

From procedural code you use: @"pack://application:,,,/putyourfilenamehere" for an embedded resource.

Or in other words

BitmapImage image = new BitmapImage(new Uri("pack://application:,,,/Images/myimage.png"));

Upvotes: 1

John
John

Reputation: 1477

It turns out that I should have used

Uri(@"pack://application:,,,/<MyProject>;component/images/tagimages/placeholder.png", UriKind.Absolute);

Upvotes: 9

Related Questions