1

我在 vb.net 中有以下代码。我正在使用 WPF,并且在 XAML 中我在图像上有一个转换器。基本上基于状态级别的图像应该显示一个特定的图像。

我在使用这种语法时遇到了问题。我在“ImageSource”上有一个错误,因为它说“New 不能在 MustInherit 的类中使用”。我尝试删除 New 并将 ImageSource 声明为字符串,但代码不会将任何内容返回到我的 XAML 中。我需要做什么?!?

    Public Function Convert(ByVal value As Object, _ 
                            ByVal targetType As System.Type, 
                            ByVal parameter As Object, 
                            ByVal culture As System.Globalization.CultureInfo) _ 
        As Object Implements System.Windows.Data.IValueConverter.Convert
    Dim EstadoIndex As Integer
    If Integer.TryParse(value.ToString, EstadoIndex) Then
        Select Case EstadoIndex
            Case 1
                Return New ImageSource("/Cogent;component/Images/Green.png")
            Case 2
                Return New ImageSource("/Cogent;component/Images/Red.png")
            Case Else
                Return New ImageSource("/Cogent;component/Images/White.png")
        End Select
    Else
        Return New ImageSource("/Cogent;component/Images/White.png")
    End If
End Function
4

3 回答 3

4

ImageSource是一个抽象类(我想MustInherit这就是你abstract在 VB.NET 中的命名方式)。如果要返回图像,可以使用BitmapImage,它将为您将图像加载到内存中,请使用new BitmapImage(new Uri("/Cogent;component/Images/Green.png"))

此外,如果您需要将其设置为Image.Source- 您可以只返回字符串,Image将加载图像。

于 2013-04-12T20:45:12.020 回答
1

感谢 OutColdMan 和 Pondidum,

我不得不做一些小偷小摸,但基本上这两个想法都在钱上。如果有人感兴趣,这是最终代码!

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
    Dim EstadoIndex As Integer
    Dim bi As New BitmapImage()
    bi.BeginInit()
    'Dim ImageSource As String = "/Cogent;component/Images/White.png"
    If Integer.TryParse(value.ToString, EstadoIndex) Then
        Select Case EstadoIndex
            Case 1
                bi.UriSource = New Uri("/Cogent;component/Images/Green.png", UriKind.RelativeOrAbsolute)
                Return bi
                bi.EndInit()
            Case 2
                bi.UriSource = New Uri("/Cogent;component/Images/Red.png", UriKind.RelativeOrAbsolute)
                Return bi
                bi.EndInit()
            Case Else
                bi.UriSource = New Uri("/Cogent;component/Images/White.png", UriKind.RelativeOrAbsolute)
                Return bi
                bi.EndInit()
        End Select
    Else
        bi.UriSource = New Uri("/Cogent;component/Images/White.png", UriKind.RelativeOrAbsolute)
        Return bi
        bi.EndInit()
    End If
End Function
于 2013-04-12T21:10:10.973 回答
0

检查MSDN 上的ImageSource表明您需要使用它的子类之一,即BitmapImage

于 2013-04-12T20:46:07.140 回答