我从SQL服务器表中查询了一个数据表 数据表只包含一列,它将包含0到9之间的数字 我需要在WPF datagrid中显示它。我已经完成了普通数据网格的显示 但是我需要在该列中显示单独的图片和该特定号码的一些文本 是否有可能通过Datagrid?
答案 0 :(得分:6)
使用DataGridTemplateColumn并使用IValueConverter
绑定它,将您的int
转换为ImageSource
这是一个小工作示例:
<强> MainWindow.xaml 强>
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:StackOverflow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:IntToImageConverter x:Key="IntToImageConverter" />
</Window.Resources>
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Converter={StaticResource IntToImageConverter}}" />
<TextBlock Text="Image number : " Margin="5, 0, 0, 0" />
<TextBlock Text="{Binding}" Margin="5, 0, 0, 0" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
<sys:Int32>0</sys:Int32>
<sys:Int32>1</sys:Int32>
</DataGrid>
</Window>
<强> MainWindow.xaml.cs 强>
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace StackOverflow
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class IntToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ImageSource result = null;
var intValue = (int)value;
switch (intValue)
{
case 0:
{
result = new BitmapImage(new Uri(@"your_path_to_image_0"));
break;
}
case 1:
{
result = new BitmapImage(new Uri(@"your_path_to_image_1"));
break;
}
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}