WPF Datagrid:根据数据源的数值,使用转换器在列中显示图像 [英] WPF Datagrid: Displaying image in column using converter based on numerical value of datasource
问题描述
我有以下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
返回的资源是位图。我知道转换器类正在触发,因为我已经在messagebox'd变量'x',它显示了数据源的游戏列中的整数值。但是,我的TemplateColumn仍然为空:
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:
我做错了什么?如果我将图像源设置为静态uri,我将在第一列中看到一个图像。但是尝试绑定和转换不起作用。
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.
推荐答案
在转换器中,尝试使用位图uri返回BitmapImage,而不是位图本身:
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()
这篇关于WPF Datagrid:根据数据源的数值,使用转换器在列中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!