Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing WPF Image Resources

For a WPF application which will need 10 - 20 small icons and images for illustrative purposes, is storing these in the assembly as embedded resources the right way to go?

If so, how do I specify in XAML that an Image control should load the image from an embedded resource?

like image 862
driis Avatar asked Dec 07 '08 14:12

driis


People also ask

What are resources in WPF?

A resource is an object that can be reused in different places in your application. WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles.

How do I insert an image in WPF XAML?

XAML. WPF image control is a versatile control. We will add the image by using the Syntax: Image Source property. Source Property: From the above example, we have seen that the Source Property is used to define the image we want to display.

How do I keep windows on top of WPF?

Topmost - The default is false, but if set to true, your Window will stay on top of other windows unless minimized.


2 Answers

If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all Image elements.

To do this, create a BitmapSource as a resource somewhere:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" /> 

Then, in your code, use something like:

<Image Source="{StaticResource MyImageSource}" /> 

In my case, I found that I had to set the Image.png file to have a build action of Resource rather than just Content. This causes the image to be carried within your compiled assembly.

like image 170
Drew Noakes Avatar answered Oct 10 '22 08:10

Drew Noakes


I found to be the best practice of using images, videos, etc. is:

  • Change your files "Build action" to "Content". Be sure to check Copy to build directory.
    • Found on the "Right-Click" menu at the Solution Explorer window.
  • Image Source in the following format:
    • "/«YourAssemblyName»;component/«YourPath»/«YourImage.png»"

Example

<Image Source="/WPFApplication;component/Images/Start.png" /> 

Benefits:

  • Files are not embedded into the assembly.
    • The Resource Manager will raise some memory overflow problems with too many resources (at build time).
  • Can be called between assemblies.
like image 31
Nuno Rodrigues Avatar answered Oct 10 '22 08:10

Nuno Rodrigues