我有一个从 SQL 服务器表中查询的数据表。
数据表仅包含一列,它将包含 0 -9 之间的数字。
我需要在 WPF 数据网格中显示它。我已经完成了作为普通数据网格的显示。
但是我需要为该列中的特定数字显示一张单独的图片和一些文本。
是否有可能通过 Datagrid?
最佳答案
使用DataGridTemplateColumn并使用 IValueConverter
将其绑定(bind),将您的 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();
}
}
}
关于c# - 基于 WPF 数据网格中的列值显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14066601/