WPF Datagrid:使用基于数据源数值的转换器在列中显示图像

时间:2011-08-21 04:42:28

标签: wpf image datagrid resources

我有以下XAML:

<Window.Resources>
    <myApp:ImageDisplayConvertor x:Key="ImageDisplayConvertor" />
</Window.Resources>

<DataGridTemplateColumn Header="Icon">
    <DataGridTemplateColumn.CellTemplate >
        <DataTemplate>
            <Image Name="img" Source="{Binding Game,Converter={StaticResource ImageDisplayConvertor}}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

这是我的转换器代码:

Public Class ImageDisplayConvertor
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim x As Integer = DirectCast(value, Integer)

        Select Case x
            Case 1 : Return My.Resources.T1
            Case 2 : Return My.Resources.T2
            Case 3 : Return My.Resources.T3_Blue
            Case 10 : Return My.Resources.SS2
            Case Else : Return My.Resources.imgError
        End Select
    End Function

    Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Return value
    End Function
End Class

返回的资源是位图。我知道转换器类正在触发,因为我已经将消息框变为“x”,并且它显示了数据源的“游戏”列中的整数值。但是,我的TemplateColumn仍为空:

我做错了什么?如果我将图像源设置为静态uri,我会在第一列中看到一个图像。但是尝试绑定和转换不起作用。

1 个答案:

答案 0 :(得分:0)

在转换器中,尝试使用位图uri而不是位图本身返回BitmapImage:

Dim bi As New BitmapImage
bi.BeginInit()
bi.UriSource = New Uri("yourBitmap.png", UriKind.Relative)
bi.EndInit()