根据WPF数据网格中的列值显示图像

时间:2012-12-28 08:15:38

标签: c# wpf visual-studio-2010 datagrid wpfdatagrid

我从SQL服务器表中查询了一个数据表 数据表只包含一列,它将包含0到9之间的数字 我需要在WPF datagrid中显示它。我已经完成了普通数据网格的显示 但是我需要在该列中显示单独的图片和该特定号码的一些文本 是否有可能通过Datagrid?

1 个答案:

答案 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();
        }
    }
}