将数据网格列绑定到列表。

5

我正在开发一个基于MVVM的WPF应用程序。我想将一个字符串列表绑定到列标题,例如,如果该列表包含"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


1
你想要能够重新排序列吗? - Markus
1
@Markus 我需要按列排序但不重新排序。 - Abhishek Batra
根据我的经验,虽然使用附加属性是可行的,但这种方法过于繁琐且限制太多,会迫使你将 UI 相关的事情转移到过程式代码中,而这些本应该在 XAML 中完成。针对每种数据类型使用特定的 XAML 定义的 DataTemplate,而不是尝试使用“一刀切”的解决方案,这种方案只适用于非常基本的仅包含字符串的数据类型。 - Federico Berasategui
1个回答

4
您可以以以下两种方式之一使用 DataGrid:
1)将 DataGrid 的 ItemsSource 绑定到一个集合,该集合包含具有 abc、xyz、pqr 3个属性的元素。
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;
        }
    }

1
这并没有回答问题,它不依赖于“Columns”,因为“MyDataItem”包含固定数量的属性,而不依赖于“Columns ObservableCollection<string>”。 - user12805184

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接