DataGrid中的KeyValuePair绑定列表,每个键都是coulmn标头

时间:2018-11-23 14:55:08

标签: c# wpf binding datagrid keyvaluepair

我有一个带有指定参数(字符串/整数)和List<KeyValuePair<string, string>>

的对象
 public class Product
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string ReferenceNumber { get; set; }
        public string Category { get; set; }
        public List<KeyValuePair<string, string>> AttributeList { get; set; }
}

我想将此对象绑定到DataGrid,但我想让KVP中的每个记录都作为Column标头和值。像这样:

AttributeList  = new List<KeyValuePair<string, string>>
{
   new KeyValuePair{"SIZE", "30"}, new KeyValuePair{"WIDTH", "50"}
}

AttributeList键在与类别不同的​​API中是静态的。一次只能有一个键列表。 我不知道如何绑定它。

1 个答案:

答案 0 :(得分:0)

您需要一个数据透视表。下面的代码创建一个DataTable,它等效于您可以绑定到的Excel数据透视表。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Product> products = new List<Product>();

            List<string> keys = products.Select(x => x.AttributeList.Select(y => y.Key)).SelectMany(x => x).Distinct().ToList();

            DataTable pivot = new DataTable();
            pivot.Columns.Add("Id", typeof(long));
            pivot.Columns.Add("Name", typeof(string));
            pivot.Columns.Add("ReferenceNumber", typeof(string));
            pivot.Columns.Add("Category", typeof(string));
            foreach (string key in keys)
            {
                pivot.Columns.Add(key, typeof(string));
            }

            foreach (Product product in products)
            {
                DataRow row = pivot.Rows.Add();
                row["Id"] = product.Id;
                row["Name"] = product.Name;
                row["ReferenceNumber"] = product.ReferenceNumber;
                row["Category"] = product.Category;
                foreach (KeyValuePair<string, string> attr in product.AttributeList)
                {
                    row[attr.Key] = attr.Value;
                }

            }

        }
    }
    public class Product
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string ReferenceNumber { get; set; }
        public string Category { get; set; }
        public List<KeyValuePair<string, string>> AttributeList { get; set; }
    }
}