WPF: Embedding Images in the Assembly
Yesterday, I searched for a possiblity to include PNGs into my assemblies and access tem from WPF/XAML. The only stuff I found was
Chad Campbell‘s “
Point an Image to an Embedded Resource“. Chad recommends using embedded resources and manually extracting them with
Assembly.GetManifestResourceStream and
PngBitmapDecoder in the code-behind. Yuck! That would mean giving every
Image a
Name and jump through hoops to share memory and what not.
Today I looked at it again and…
thought I should be able to create a custom
System.Windows.Media.ImageSource using a hidden
BitmapSource for XAML usage. Far from it! While
ImageSource is
public abstract, it uses some “private parts” from
Windows.Media.Composition.DUCE which are not available to the common folk.
Finally uncle google came to the rescue: in a microsoft forum posting (“
Using Bitmap resources from .resx file in WPF“)
Ashish Shetty explains how to use a special URI syntax to access resources directly from XAML. The catch is that the images have to be built as “
Resource” and not as “
Embedded Resource“. This seems to be only available if the assembly was created from one of the WPF project templates[1]. But if everything is done right, the resource can be accessed by simply setting the “
Source” property:
<!-- local assembly -->
<image Source="/directory/foo.png" />
<!-- referenced assembly -->
<image Source="/AssemblyName;component/directory/foo.png" />
More details can be found in the MSDN article “
Windows Presentation Foundation Application Resource, Content, and Data Files“.
[1] See the last comment at
How to use resources (images) in dll assembly?