0

我有一个 WPF 应用程序,我在项目资源中添加了许多图标和位图。

现在我可以像这样访问它们:

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

为了在 wpf 中使用它,我创建了将它们转换为 ImageSource 类型的过于简单的扩展方法:

'...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

所以我可以这样使用它:

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

看一下 MyWpfExtensions.vb,我发现很少有 Microsoft 基础设施允许非官方编码,这是我向各位专家提出的问题。

我想为 System.Drawing.Bitmap/Icon 类型的每个资源提供一个附加(或覆盖)属性,该属性通过 ex 返回图像。方法,所以我不必在 Xaml 中使用转换器,而是直接使用它。

我实际上正在寻找类似 Microsoft.VisualBasic.MyGroupCollectionAttribute 的东西。

有任何想法吗?...

4

1 回答 1

0

我想除了转换器之外别无他法,所以让我们发布它:

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
于 2009-09-14T08:10:46.413 回答