1
votes

I develop an IOC framework in the form of a DLL that creates the application's main window and displays various WPF Pages in it. There is a folder of PNG images with their Build Action set to Resource. I use code like this to set the sources of WPF Image elements...

MyImage.Source = new BitmapImage(new Uri("/MyAssembly;component/Images/MyImage.png", UriKind.Relative));

This works great. However, there is also a feature where the user can choose to display one of these WPF Pages in a separate window. Here is the mystery: If the user navigates to the page in the main window before showing it in a separate window, all is well. However, if the user shows the page in a separate window before it is shown in the main window, I get a DirectoryNotFoundException saying " Could not find a part of the path 'C:\MyAssembly;component\Images\MyImage.png'."

I discovered the OnLoad cache option and tried the following code...

var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri("/MyAssembly;component/Images/MyImage.png", UriKind.Relative);
image.EndInit();
MyImage.Source = image;

However, I then get the DirectoryNotFoundException on the very first image that I attempt to create.

I also tried an absolute URI...

MyImage.Source = new BitmapImage(new Uri("pack://application:,,,/MyAssembly;component/Images/MyImage.png", UriKind.Absolute));

I then get a UriFormatException saying "Invalid URI: Invalid port specified."

1
Thanks for the update. You should put that as an official answer to the question. - RandomEngy
I intend to. Stack Overflow says that I have to wait 8 hours because I'm a new member. - Bruce Greene
Ahh right. Welcome! Good to have another person who writes clear questions on here. :) - RandomEngy

1 Answers

1
votes

I solved the problem by using the 'pack' URI format as shown in the question. However, I needed to make a call to the Application class before I did so. This has the effect of executing the Application's static constructor which registers the 'pack' URI scheme. I found my answer here. The call I used was simply this:

var app = Application.Current;