【问题标题】:How to attach properties (thru .NET infrastracture or any else)如何附加属性(通过 .NET 基础设施或任何其他)
【发布时间】:2009-09-14 01:48:35
【问题描述】:

我有一个 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 类型的资源添加一个附加(或覆盖)属性,该属性通过前返回图像。方法,所以我不必在 Xaml 中使用转换器,而是直接使用它。

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

有什么想法吗?...

【问题讨论】:

    标签: .net properties infrastructure


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      相关资源
      最近更新 更多