【问题标题】:WPF add datagrid image column possible?WPF添加datagrid图像列可能吗?
【发布时间】:2013-03-18 23:28:29
【问题描述】:

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

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

代码如下:

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 行代码添加一个可以处理图像的列。在 WPF 中,我看到它有点不同。我需要添加一个“图像列”吗?或者 WPF 列是否支持图像?还是有另一种语法不同的 3 班轮解决方案?

感谢大家的帮助

【问题讨论】:

  • WPF 允许您将任何您想要的内容放入控件中。您可以将整个自定义控件放在一列或原始类型中
  • 哇,所以基本上我可以跳过这部分,只需添加一个新列并将图像添加到该列?不需要指定的列类型?
  • 您只需将变量绑定到列,它就会从您添加到行的对象中加载该图像

标签: c# wpf datagrid


【解决方案1】:

看到这个答案:

Image Column in WPF DataGrid

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

在代码之后添加一列:

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

使用DataGridTemplateColumn 添加自定义列 见:How do I show image in wpf datagrid column programmatically?

【讨论】:

  • 哦,使用 xaml...如果可能的话,我想避免使用 xaml 并坚持使用 c# 代码,或者这只是 wpf 中的坏习惯?
  • WPF 是为了使用 XAML 而创建的。它让生活变得更轻松,并且没有理由自己编写代码 :) 在创建 xaml 后,您始终可以查看自动化源代码,以了解在幕后执行了哪些操作来实现它
  • 那么 datgrid 将需要 3 个新列,这些列在运行时纯粹为用户生成。然后使用公式计算每一行,然后根据公式结果在每行的这些新列中显示正确的图像。这个例子对我来说似乎是静态的,还是我根本无法理解?
  • 您也可以在代码中创建它,或者在 xaml 中创建图像列,因为您知道它在那里并在事后添加其他列
  • 供其他新手阅读。是的@lemunk 没有按照他的建议理解。它不需要是静态的。绑定将决定在运行时显示的图像。
【解决方案2】:

这里是 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>

在此之后是我的 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:\1.jpg")), stu_name = "abc" });
                    stu.Add(new StudentData() { image = toBitmap(File.ReadAllBytes(@"D:\1.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; }
            }
        }

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

【讨论】:

    【解决方案3】:

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

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

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

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

    现在您要做的就是绑定提供“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;
    

    【讨论】:

      【解决方案4】:

      您可以尝试通过以下模式将 Image 添加到 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        • 1970-01-01
        • 2016-05-12
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多