I wanted to offer the solution I've come up with:
public static class IconExtensions
{
[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteObject(IntPtr hObject);
public static ImageSource ToImageSource(this Icon icon)
{
Bitmap bitmap = icon.ToBitmap();
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
if (!DeleteObject(hBitmap))
{
throw new Win32Exception();
}
return wpfBitmap;
}
}
I then have a IconToImageSourceConverter that simply calls the method above.
To make it easy for me to add icons as images I also added this:
<DataTemplate DataType="{x:Type drawing:Icon}">
<Image Source="{Binding Converter={converter:IconToImageSourceConverter}}"
MaxWidth="{Binding Width}" MaxHeight="{Binding Height}"/>
</DataTemplate>
This way, if an icon is placed directly in XAML if will still be shown:
<x:Static MemberType="{x:Type drawing:SystemIcons}" Member="Asterisk"/>
Otherwise the converter can be used on location, like so:
<Image Source="{Binding Source={x:Static drawing:SystemIcons.Asterisk},
Converter={converter:IconToImageSourceConverter}}"/>