在Dev的GridControl控件的列中显示图片

(图片来自Silverlight项目的资源中)
步骤:
1. 实现转换类
public class UserIDToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter.ToString() == "text")
{

return (int)value + 10000;
}

if (parameter.ToString() == "DataGrid")
{
BitmapImage bi = new BitmapImage(new Uri("Images/Tulips.jpg", UriKind.Relative));
if ((int)value == 101)
bi = new BitmapImage(new Uri("Images/Penguins.jpg", UriKind.Relative));

if ((int)value == 102)
bi = new BitmapImage(new Uri("Images/Koala.jpg", UriKind.Relative));

return bi;
}

if (parameter.ToString() == "GridControl")
{
BitmapImage bi = new BitmapImage(new Uri("Images/Tulips.jpg", UriKind.Relative));
//return bi;
if ((int)value == 101)
bi = new BitmapImage(new Uri("Images/Penguins.jpg", UriKind.Relative));

if ((int)value == 102)
bi = new BitmapImage(new Uri("Images/Koala.jpg", UriKind.Relative));
Image image = new Image();
image.Source = bi;

return bi;
}
return value;

}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return 333;
//return new BitmapImage(new Uri("Images/Tulips.jpg", UriKind.Relative));
}
}
1.1 此类可单独在一个cs文件中或直接放在其他cs文件中。
1.2 在convert方法中根据传递的参数paramter不同返回不同的值,可以用一个转换类实现多个转换要求,省得每种转换实现一个转换类。
2. 在XAML文件中引用转换类
xmlns:convert="clr-namespace:slqmis"
slqmis是项目的名字。
3.在XAML文件中建立转换类的映射关系。
<UserControl.Resources>
<convert:UserIDToImageConverter x:Key="converter"/>
</UserControl.Resources>
UserIDToImageConverter是转换类的名字,converter是在XAML文件中被使用时定义的名字
4. 在GridColumn中显示图片代码
<dxg:GridColumn FieldName="msUserID" Header="UserID" Name="gcUserID">
<dxg:GridColumn.DisplayTemplate>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<Image Name="PART_Editor" Height="60" Width="66" HorizontalAlignment="Left" Source="{Binding Path=EditValue, Converter={StaticResource converter}, ConverterParameter=GridControl}" Stretch="Fill" VerticalAlignment="Top"/>
<TextBlock Text="{Binding Path=EditValue}" />
</StackPanel>
</ControlTemplate>
</dxg:GridColumn.DisplayTemplate>
</dxg:GridColumn>
如果GridControl仅用于显示不编辑应使用GridColumn的显示模板(DisplayTemplate),如果要改变GridColumn的结构需用CellTemplate模板,如果要编辑需用EditTemplate。需注意Image中Source要绑定到EditValue上。

5. 在DataGrid中实现此功能1、2、3步骤一样,第四步不同:
<sdk:DataGridTemplateColumn Header="msUserID" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Name="PART_Image1" Height="60" Width="66" HorizontalAlignment="Left" Source="{Binding Path=msUserID, Converter={StaticResource converter}, ConverterParameter=DataGrid}" Stretch="Fill" VerticalAlignment="Top"/>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
原文地址:https://www.cnblogs.com/wpf123/p/2224620.html