views:

105

answers:

1

I have a WPF application and I added to the project resources many icons and bitmaps.

Now I can access them like this:

Dim ico As System.Drawing.Icon = My.Resources.Icon 'Icon.ico
Dim img As System.Drawing.Bitmap = My.Resources.Image 'Image.png

In order to use it in wpf I created too simple Extension Methods that convert them to ImageSource type:

'...Imports System.Drawing
'...Imports System.Windows.Interop.Imaging
<Extension()> _
Public Function ToImageSource(ByVal icon As Icon) As BitmapSource
    Return CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, _
        BitmapSizeOptions.FromEmptyOptions)
End Function

<Extension()> _
Public Function ToImageSource(ByVal image As Bitmap) As BitmapSource
    Return CreateBitmapSourceFromHBitmap(image.GetHbitmap(), IntPtr.Zero, _
        Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions)
End Function

So I can use it this way:

Dim i As New Image With {.Source = My.Resources.Image.ToImageSource}

Taking a look at MyWpfExtensions.vb reveals me that there are few Microsoft infrastractures that allow unofficial coding and here comes my question to the experts of you.

I'd like to have for each resource of type System.Drawing.Bitmap/Icon an additional (or overriding) property that returns the image via the ex. method so I don't have to use a converter in the Xaml, but use it directly.

I am actually looking for something like Microsoft.VisualBasic.MyGroupCollectionAttribute.

Any ideas?...

A: 

I guess there is not other way but a converter so let's post it:

Imports System.Drawing
Namespace Converters
    <ValueConversion(GetType(MarshalByRefObject), GetType(BitmapSource))> _
    Public Class ImageSourceConverter : Implements IValueConverter
        Public Function Convert(value As Object, targetType As Type, 
        parameter As Object,
        culture As System.Globalization.CultureInfo) As Object
        Implements System.Windows.Data.IValueConverter.Convert
            Dim imageSource As ImageSource = Nothing
            Dim type = value.GetType
            If type.Equals(GetType(Icon)) Then
                imageSource = DirectCast(value, Icon).ToImageSource
            ElseIf type.Equals(GetType(Bitmap)) Then
                imageSource = DirectCast(value, Bitmap).ToImageSource
            End If

            Return imageSource
        End Function

        Public Function ConvertBack(value As Object, targetType As Type,
        parameter As Object,
        culture As System.Globalization.CultureInfo) As Object Implements
        System.Windows.Data.IValueConverter.ConvertBack
            Throw New NotSupportedException
        End Function
    End Class
End Namespace
Shimmy