Sam
Sam

Reputation: 29009

Convert System.Drawing.Image resource into System.Windows.Controls.Image for wpf MenuItem

I've got resources in my assembly which I can Access using Properties.Resources.MyImage.
And I have some class which I bind to a WPF MenuItem containing a property

public System.Windows.Controls.Image Icon {get; set;}

This I want to set programmatically using:

dummy.Icon = Properties.Resources.MyImage;

Now I want to convert the resource System.Drawing.Image to the WPF System.Windows.Controls.Image. I thought this should be straightforward, but I found no working solution for my Images (which are png files using transparency).

So how do I convert System.Drawing.Image into System.Windows.Controls.Image?

Upvotes: 1

Views: 2362

Answers (1)

Eli Arbel
Eli Arbel

Reputation: 22749

Instead of using Properties.Resources, which are Windows Forms Embedded Resources, use WPF resources. In Solution Explorer, click the image file and in the properties window, set its Build Action to Resource (not Embedded Resource). This also embeds the image into the assembly, but in a different way.

Unlike Windows Forms, WPF does not generate a resource manager class, so you'd have to use strings to load the images dynamically:

BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri("pack://application:,,,/NameOfAssembly;component/Path/To/Image.png");
image.EndInit();

Note the application and component parts of the URI are constant strings, while NameOfAssemly is the name of the assembly where the image is in. You can build a helper class that builds the URI and loads images.

You can also call image.Freeze() if you don't plan on making any changes to the image (improves performance and allows image source to be created on non-UI threads).

In your data class, expose an ImageSource property instead of an Image. Then you use the Image control to display it:

<Image Source="{Binding Icon}" />

Or inside a style:

<Style TargetType="MenuItem">
    <Style.Resources>
        <Image x:Key="Icon"
                x:Shared="False"
                Source="{Binding Icon}"
                Width="16"
                Height="16" />
    </Style.Resources>
    <Setter Property="Icon" Value="{StaticResource Icon}" />
</Style>

Upvotes: 2

Related Questions