将DataGrid列绑定到列表

本文关键字:列表 绑定 DataGrid | 更新日期: 2023-09-27 18:10:02

我正在开发一个基于MVVM的WPF应用程序。我想绑定一个列表的字符串列标题ie。,如果列表包含"abc","xyz","pqr",那么我的DataGrid应该有三列,标题为abc, xyz, pqr。这是我将数据网格绑定到的类。行存储在ObservableCollection<List<string>>中,ObservableCollection的每个元素是一个字符串列表,它构成了行的单元格。

public class Resource
{
    private ObservableCollection<string> columns;
    public ObservableCollection<string> Columns
    {
        get
        {
            return columns;
        }
        set
        {
            columns = value;
        }
    }
    private ObservableCollection<List<string>> row;
    public ObservableCollection<List<string>> Row
    {
        get
        {
            return row;
        }
        set
        {
            row = value;
        }
    }
    public Resource()
    {
        List<string> a = new List<string>();
        a.Add("1");
        a.Add("2");
        List<string> b = new List<string>();
        b.Add("11");
        b.Add("21");
        Row = new ObservableCollection<List<string>>();
        Row.Add(a);
        Row.Add(b);
        Columns = new ObservableCollection<string>();
        Columns.Add("Hello");
        Columns.Add("World");
    }
}

我已经搜索了互联网很多,但找不到任何工作的例子。我只需要用这个方法绑定DataGrid

将DataGrid列绑定到列表

您可以通过以下两种方式之一使用DataGrid:

1)将DataGrid的ItemsSource绑定到一个暴露3个属性abc, xyz, pqr的元素集合。

CS:

    public List<MyDataItem> DataItems 
    {
        get
        {
            List<MyDataItem> items = new List<MyDataItem>(5);
            for (int i = 0; i < 5; i++)
            {
                items.Add(new MyDataItem { abc = abc[i], qrt = qrt[i], xyz = xyz[i] });
            }
            return items;
        }
    }
    int[] abc = new int[5] { 1, 2, 3, 4, 5 };
    int[] qrt = new int[5] { 6,7,8,9,10 };
    int[] xyz = new int[5] { 11,12,13,14,15};

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
public class MyDataItem
{
    public int abc { get; set; }
    public int qrt { get; set; }
    public int xyz { get; set; }
}

XAML:

 <DataGrid ItemsSource="{Binding DataItems}" />    
2)创建一个DataTable对象并将其绑定到ItemsSource。
 public DataTable DataTable
    {
        get
        {
            DataTable table = new DataTable();
            table.Columns.Add("abc");
            table.Columns.Add("qrt");
            table.Columns.Add("xyz");
            table.Rows.Add(1, 6, 11);
            table.Rows.Add(2, 7, 12);
            table.Rows.Add(3, 8, 13);
            table.Rows.Add(4, 9, 14);
            table.Rows.Add(5, 10, 15);
            return table;
        }
    }