如何附加属性(通过.NET基础结构或任何其他)

时间:2009-09-14 01:48:35

标签: .net properties infrastructure

我有一个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,我发现微软的基础设施很少允许非官方编码,这就是我向你的专家提出的问题。

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

我实际上正在寻找像Microsoft.VisualBasic.MyGroupCollectionAttribute这样的东西。

任何想法?...

1 个答案:

答案 0 :(得分: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