Search code examples
wpfembedded-resourceresx

How to use a localizable resx image in WPF?


I have a bunch of localizable images and icons in the standard Properties.Resources.resx file; they are mostly linked at compile time. I want to put them on some WPF controls.

In WinForms,

control.Image = Properties.Resources.ImageResourceName;

does the trick, is maintainable, localizable, not susceptible to refactoring, and can be done using only the Windows Forms designer, but I just can't figure out how to achieve similar results in WPF (xaml OR code).


Solution

  • What is stored in your resx file is a Drawing.Bitmap. You can convert it into a BitmapSource using the code below. This code could be placed in a converter for example. Personnaly, I have defined a MarkupExtension that take the name of the resx and the name of the ressource and call this code.

    private BitmapSource bitmapToSource(System.Drawing.Bitmap bitmap)
    {
        BitmapSource destination;
        IntPtr hBitmap = bitmap.GetHbitmap();
        BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions();
        destination = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions);
        destination.Freeze();
        return destination;
    }