• WPF中的DataGrid如何动态生成列表列?
  • 发布于 2个月前
  • 247 热度
    0 评论
在日常开发中,DataGrid作为二维表格,非常适合数据的展示和统计。通常情况下,一般都有固定的格式和确定的数据列展示,但是在某些特殊情况下,也可能会需要用到动态生成列。本文以一些简单的小例子,简述在WPF开发中,如何动态生成DataGrid的行和列,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点
在本示例中,用到的知识点如下所示:
1.CommunityToolkit.Mvvm,微软提供的一个基于.Net的MVVM框架库,通过此库,可以方便是实现数据绑定和命令绑定,达到前后端分离的目的。
2.ObservableCollection ,相比较于List,当列表中的数据条数发生变化时,会自动进行通知,实现数据的实时更新。
3.DataTable,表示内存的一个数据表格,可以动态创建列,并自动绑定到DataGrid中。
4.ExpandoObject 表示一个动态对象,其内容可以动态添加和删除。

普通绑定
将ViewModel中的列表对象,绑定到View页面中的DataGrid,实现步骤如下:

1. 创建模型
创建绑定到DataGrid中的对象模型,如下所示:
public class Student
{
  /// <summary>
  /// 唯一标识
  /// </summary>
  public int Id { get; set; } 
 
  /// <summary>
  /// 姓名
  /// </summary>
  public string Name { get; set; }
 
  /// <summary>
  /// 年龄
  /// </summary>
  public int Age { get; set; }
 
  /// <summary>
  /// 性别
  /// </summary>
  public string Gender { get; set; }
 
  /// <summary>
  /// 地址
  /// </summary>
  public string Addr { get; set; }
}
2. 创建数据源列表对象
创建要绑定到视图层的列表对象Students,并赋值,如下所示:
public class GeneralBindingViewModel:ObservableObject
{
  private ObservableCollection<Student> students;
 
  public ObservableCollection<Student> Students
  {
    get { return students; }
    set { SetProperty(ref students, value); }
  }
 
  public GeneralBindingViewModel()
  {
    Students=new ObservableCollection<Student>();
  }
 
  #region Loaded命令
 
  private ICommand winLoadedCommand;
 
  public ICommand WinLoadedCommand
  {
    get
    {
      if (winLoadedCommand == null)
      {
        winLoadedCommand = new RelayCommand<object>(WinLoaded);
      }
      return winLoadedCommand;
    }
  }
 
  private void WinLoaded(object sender)
  {
    if (sender != null)
    {
 
    }
    if (Students == null || Students.Count < 1)
    {
      var parentName = new string[5] { "张", "王", "李", "赵", "刘" };
      var province = new string[5] { "河南", "江苏", "河北", "湖北", "福建" };
      for (int i = 0; i < 20; i++)
      {
        var student = new Student()
        {
          Id = i,
          Name = parentName[(i % 4)] + i.ToString().PadLeft(2, 'A'),
          Age = 20 + (i % 5),
          Gender = i % 2 == 0 ? "男" : "女",
          Addr = province[(i % 4)]
        };
        this.Students.Add(student);
      }
    }
  }
 
  #endregion
}
3. 视图绑定
在UI视图中,为DataGrid的ItemsSource属性绑定数据源,如下所示:
<Window x:Class="DemoDynamicBinding.GeneralBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DemoDynamicBinding"
        mc:Ignorable="d"
        Title="基础绑定" Height="450" Width="800">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding WinLoadedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Grid>
        <DataGrid ItemsSource="{Binding Students}" CanUserAddRows="False" CanUserDeleteRows="False" ColumnWidth="*" ColumnHeaderHeight="30" RowHeight="25" AlternationCount="2" AlternatingRowBackground="AliceBlue" RowBackground="#ffffee">
            
        </DataGrid>
    </Grid>
</Window>
4. 关联视图层和ViewModel层
在视图文件对应的cs文件中,创建ViewModel对象实例并赋值给视图的DataContext属性,如下所示:
public partial class GeneralBinding : Window
{
  private GeneralBindingViewModel viewModel;
 
  public GeneralBinding()
  {
    InitializeComponent();
    if(viewModel == null)
    {
      viewModel = new GeneralBindingViewModel();
      this.DataContext = viewModel;
    }
  }
}
动态生成列
在WPF开发中,动态生成DataGrid列,共有两种方式:
1. DataTable作为数据源
通过DataTable作为数据源,可以不用创建模型,也不需要使用ObservableCollection对象,直接使用DataTable作为数据承载对象,DataGrid会根据DataTable的Columns列表自动生成列。如下所示:
public class DataTableBindingViewModel:ObservableObject
{
  private DataTable students;
 
  public DataTable Students
  {
    get { return students; }
    set { SetProperty(ref students , value); }
  }
 
  public DataTableBindingViewModel()
  {
    Students = new DataTable();
  }
 
  #region Loaded命令
 
  private ICommand winLoadedCommand;
 
  public ICommand WinLoadedCommand
  {
    get
    {
      if (winLoadedCommand == null)
      {
        winLoadedCommand = new RelayCommand<object>(WinLoaded);
      }
      return winLoadedCommand;
    }
  }
 
  private void WinLoaded(object sender)
  {
    if (sender != null)
    {
 
    }
    if (Students == null || Students.Rows.Count < 1)
    {
      var students = new DataTable();
      students.Columns.Add("Id",typeof(int));
      students.Columns.Add("Name", typeof(string));
      students.Columns.Add("Age", typeof(int));
      students.Columns.Add("Gender", typeof(string));
      students.Columns.Add("Addr", typeof(string));
      var parentName = new string[5] { "张", "王", "李", "赵", "刘" };
      var province = new string[5] { "河南", "江苏", "河北", "湖北", "福建" };
      
      for (int i = 0; i < 20; i++)
      {
        var dr = students.NewRow();
        dr["Id"] = i;
        dr["Name"] = parentName[(i % 5)] + i.ToString().PadLeft(2, 'A');
        dr["Age"] = 20 + (i % 5);
        dr["Gender"] = i % 2 == 0 ? "男" : "女";
        dr["Addr"] = province[(i % 5)];
         
        students.Rows.Add(dr);
      }
      this.Students= students;
    }
  }
 
  #endregion
 
}
2. ExpandoObject作为模型
ExpandoObject是dynamic类型,可以在运行时动态的添加和删除内容。ExpandoObject对象支持Key=Value形式,并可以对Key进行绑定。如下所示:
public class DynamicBindingViewModel : ObservableObject
{
  private ObservableCollection<ExpandoObject> students;
 
  public ObservableCollection<ExpandoObject> Students
  {
    get { return students; }
    set { SetProperty(ref students , value); }
  }
 
  private DataGrid dataGrid;
 
 
  public DynamicBindingViewModel()
  {
    this.Students = new ObservableCollection<ExpandoObject>();
  }
 
  #region Loaded命令
 
  private ICommand winLoadedCommand;
 
  public ICommand WinLoadedCommand
  {
    get
    {
      if (winLoadedCommand == null)
      {
        winLoadedCommand = new RelayCommand<object>(WinLoaded);
      }
      return winLoadedCommand;
    }
  }
 
  private void WinLoaded(object sender)
  {
    if (sender != null)
    {
      var control = sender as DynamicBinding;
      if (control != null)
      {
        this.dataGrid = control.dgTest;
      }
    }
    if (Students == null || Students.Count < 1)
    {
      var parentName = new string[5] { "张", "王", "李", "赵", "刘" };
      var province = new string[5] { "河南", "江苏", "河北", "湖北", "福建" };
      for (int i = 0; i < 20; i++)
      {
        dynamic item = new ExpandoObject();
        item.Id=i.ToString();
        item.Name = parentName[(i % 5)] + i.ToString().PadLeft(2, 'A');
        item.Age = 20 + (i % 5);
        item.Gender = i % 2 == 0 ? "男" : "女";
        item.Addr = province[(i % 5)];
        this.Students.Add(item);
      }
      //添加列
      this.dataGrid.Columns.Add(new DataGridTextColumn() { Header = "学号", Binding = new Binding("Id") });
      this.dataGrid.Columns.Add(new DataGridTextColumn() { Header = "姓名", Binding = new Binding("Name") });
      this.dataGrid.Columns.Add(new DataGridTextColumn() { Header = "年龄", Binding = new Binding("Age") });
      this.dataGrid.Columns.Add(new DataGridTextColumn() { Header = "性别", Binding = new Binding("Gender") });
      this.dataGrid.Columns.Add(new DataGridTextColumn() { Header = "地址", Binding = new Binding("Addr") });
    }
  }
 
  #endregion
}
示例效果
以上三种方式,实现的效果都是一致的,只是分别应用到不同的场景中,如下所示:

用户评论