C# WPF添加数据网格图像列可能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15683314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:34:29  来源:igfitidea点击:

WPF add datagrid image column possible?

c#wpfdatagrid

提问by lemunk

Using C#.Net 4.5, Visual Studio 2012 Ulti, WPF.

使用 C#.Net 4.5、Visual Studio 2012 Ulti、WPF。

I've got some old win-forms code that i wanted to do in this new WPF app.

我有一些旧的 win-forms 代码,我想在这个新的 WPF 应用程序中执行这些代码。

code is the following:

代码如下:

DataGridViewImageCell pNew = new DataGridViewImageCell();

ParetoGrid.Columns.Add(new DataGridViewImageColumn() { CellTemplate = pNew, FillWeight = 1, HeaderText = "pNew", Name = "pNew", Width = 30 });

ParetoGrid.Columns["pNew"].DisplayIndex = 18;

3 lines of code to add a column that can handle images. In WPF I've seen its a bit different. Do i need to add an "image column"? or does WPF columns support images? or is there another 3 liner solution that is simply different syntax?

3行代码添加一个可以处理图像的列。在 WPF 中,我看到它有点不同。我需要添加一个“图像列”吗?还是 WPF 列支持图像?还是有另一种语法不同的 3 行解决方案?

Thanks for the help guys

谢谢你们的帮助

采纳答案by JeremyK

See this answer:

看到这个答案:

Image Column in WPF DataGrid

WPF DataGrid 中的图像列

 <DataGridTemplateColumn Header="Image" Width="SizeToCells"
 IsReadOnly="True">
   <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
           <Image Source="{Binding Image}" />
      </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

To add a column in code after:

要在代码中添加一列,请执行以下操作:

DataGridTextColumn textColumn1 = new DataGridTextColumn();
textColumn1.Header = "Your header";
textColumn1.Binding = new Binding("YourBindingField");
dg.Columns.Add(textColumn1);

Use DataGridTemplateColumnto add a custom column See: How do I show image in wpf datagrid column programmatically?

使用DataGridTemplateColumn添加自定义列中看到:如何显示图像在WPF编程DataGrid列?

回答by Syed Taimoor Hussain

Here is MainWindow.xaml's code just simple for better understanding

这是 MainWindow.xaml 的代码只是为了更好地理解

`

`

<Window x:Class="Pic_in_Datagrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Pic_in_Datagrid"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <DataGrid x:Name="dt1" ColumnWidth="*" AutoGenerateColumns="False">

        </DataGrid>
    </Grid>
</Window>

After it here is my MainWindow.xaml.cs's code for image or text for adding in datadrid dynamically...

在它之后是我的 MainWindow.xaml.cs 的图像或文本代码,用于动态添加 datadrid...

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Controls;    
namespace Pic_in_Datagrid
        {
            /// <summary>
            /// Interaction logic for MainWindow.xaml
            /// </summary>
            public partial class MainWindow : Window
            {
                public StudentData stu_data { get; set; }
                public MainWindow()
                {
                    InitializeComponent();
                    stu_data = new StudentData();

                    List<StudentData> stu = new List<StudentData>();
                    stu.Add(new StudentData() { image = toBitmap(File.ReadAllBytes(@"D:.jpg")), stu_name = "abc" });
                    stu.Add(new StudentData() { image = toBitmap(File.ReadAllBytes(@"D:.jpg")), stu_name = "def" });



                    FrameworkElementFactory factory = new FrameworkElementFactory(typeof(System.Windows.Controls.Image));
                    Binding bind = new System.Windows.Data.Binding("image");//please keep "image" name as you have set in your class data member name
                    factory.SetValue(System.Windows.Controls.Image.SourceProperty, bind);
                    DataTemplate cellTemplate = new DataTemplate() { VisualTree = factory };
                    DataGridTemplateColumn imgCol = new DataGridTemplateColumn()
                    {
                        Header = "image", //this is upto you whatever you want to keep, this will be shown on column to represent the data for helping the user...
                        CellTemplate = cellTemplate
                    };
                    dt1.Columns.Add(imgCol);

                    dt1.Columns.Add(new DataGridTextColumn()
                    {
                        Header = "student name",
                        Binding = new Binding("stu_name") //please keep "stu_name" as you have set in class datamember name
                    });

                    dt1.ItemsSource = stu;    
                }

                public static BitmapImage toBitmap(Byte[] value)
                {
                    if (value != null && value is byte[])
                    {
                        byte[] ByteArray = value as byte[];
                        BitmapImage bmp = new BitmapImage();
                        bmp.BeginInit();
                        bmp.StreamSource = new MemoryStream(ByteArray);
                        bmp.EndInit();
                        return bmp;
                    }
                    return null;
                }
            }

           public class StudentData
           {
                    public BitmapImage image { get; set; }
                    public string stu_name { get; set; }
            }
        }

The above all code is taken from different resources... Thanks to them who developed and shared these codes...

以上所有代码均取自不同资源......感谢他们开发和共享这些代码......

回答by Hadeed Ullah

Here is what I did. Add a datatemplate in your datagrid with image control like this

这是我所做的。使用像这样的图像控件在数据网格中添加数据模板

            <DataGridTemplateColumn Header="File Type" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Height="25" Width="50" Source="{Binding FileIcon}"  />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

As you can see my I am binding Image with a property named "FileIcon" that is used in class Version like this

如您所见,我正在将 Image 与一个名为“FileIcon”的属性绑定,该属性在类 Version 中使用,如下所示

            public class Version
            {
              public string FileIcon { get; set; }
            }

Now only this you have to do is bind provide a path to "FileIcon" and update ItemSource of DataGrid like this

现在你唯一要做的就是绑定提供一个路径到“FileIcon”并像这样更新DataGrid的ItemSource

            ObservableCollection<Version> items = new ObservableCollection<Version>();

            items.Add(new Version()
            {
                FileIcon = "/AssemblyName;component/Images/eye.png",
            });
            YourDataGrid.ItemsSource = null;
            YourDataGrid.ItemsSource = items;

回答by lison

You may try add Image to DataGridTextColumn via pattern bellow. You may sorting and copy to clipboard works well. Use your converter, or binding to your property.

您可以尝试通过下面的模式将图像添加到 DataGridTextColumn。您可以排序并复制到剪贴板效果很好。使用您的转换器,或绑定到您的财产。

<DataGridTextColumn  Header="Level"  IsReadOnly="True" Binding="{Binding Level,Converter={StaticResource LogLevelStringConverter}}"   >
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell" >
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridCell">
                        <Grid Background="{TemplateBinding Background}" >
                            <ContentPresenter VerticalAlignment="Center" Margin="20,0,0,0" HorizontalAlignment="Left"  />
                            <Image Grid.Column="0" Width="18" Height="18" Source="{Binding Level,Converter={StaticResource LogLevelIconConverter}}"  HorizontalAlignment="Left" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>