How to reference image resources in XAML?
I put an Image
control on a Window and I would like to display an image that is stored in a project resource file named "Resources.resx". The name of the image in the resource file is 'Search'.
Could someone show me how I might go about doing this?
Solution 1:
If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:
"pack://application:,,,/Resources/Search.png"
Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:
ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"
when I have a folder named RibbonImages under Resources folder.
Solution 2:
If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:
<Image Source="/Icons/play_small.png" />
That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:
var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;
var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
this.image1.Source = bitmapImage;
Solution 3:
One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.
Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images"
Set your Image source like this:
<Image Source={Binding {x:Static UI:Resources.Search}} />
where 'Search' is name of the resource.
Solution 4:
- Add folders to your project and add images to these through "Existing Item".
- XAML similar to this:
<Image Source="MyRessourceDir\images\addButton.png"/>
- F6 (Build)