Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind images from Properties.Resources in Xaml?

Tags:

c#

.net

image

wpf

xaml

I have some images added to Properties.Resources, where I can access them like:

Properties.Resources.LayerIcon;

and want to use it in Xaml, but don't know how to do this.

I know there are different ways for images to be added into a WPF project, but I need to use Properties.Resources, because that's the only way I found where the images show up, when the application is launched via reflection.

like image 437
Joan Venge Avatar asked Feb 03 '26 13:02

Joan Venge


1 Answers

The images in Properties.Resources are of type System.Drawing.Bitmap, but WPF uses System.Windows.Media.ImageSource. You can create a converter:

[ValueConversion(typeof(System.Drawing.Bitmap), typeof(ImageSource))]
public class BitmapToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var bmp = value as System.Drawing.Bitmap;
        if (bmp == null)
            return null;
        return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmp.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

And use it as follows:

<Image Source="{Binding Source={x:Static prop:Resources.LayerIcon}, Converter={StaticResource bitmapToImageSourceConverter}}" />

Make sure your Resource is set to public and not internal.

like image 109
Thomas Levesque Avatar answered Feb 06 '26 02:02

Thomas Levesque