WPF Datagrid: Displaying image in column using converter based on numerical value of datasource
I have the following XAML:
<Window.Resources>
<myApp:ImageDisplayConvertor x:Key="ImageDisplayConvertor" />
</Window.Re开发者_运维问答sources>
<DataGridTemplateColumn Header="Icon">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<Image Name="img" Source="{Binding Game,Converter={StaticResource ImageDisplayConvertor}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Here is my Converter code:
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
The resources returned are bitmaps. I know the converter class is firing because i've messagebox'd the variable 'x' and it displays the value of the integer from the 'Game' column of the datasource. However, my TemplateColumn remains empty:
What am I doing wrong? If I set the image source to a static uri, I see an image in the first column. But trying to bind and convert doesn't work.
In your converter, try returning a BitmapImage with the bitmap uri instead of the bitmap itself:
Dim bi As New BitmapImage
bi.BeginInit()
bi.UriSource = New Uri("yourBitmap.png", UriKind.Relative)
bi.EndInit()
精彩评论