首页 > 解决方案 > DGV 数据绑定以及来自“嵌套”二级属性类的集合?

问题描述

可以将这种数据结构绑定到 DGV 上吗?

public class ClassA
{
    public string propertyA { get; set; }
    public string propertyB { get; set; }
    public ClassB propertyC { get; set; }
}

// This class acts like a preset uniform list, just to add extra columns
public class ClassB
{
    public static List<string> namesForEveryClassC { get; private set; } // Also every column header and set by the user
    private List<ClassC> data { get; set; } // Bind this

    public ClassC this[string name]
    {
        get
        {
            foreach (ClassC item in this.data)
                if (item.name == name)
                    return item;
            return null;
        }
    }

    public ClassB()
    {
        foreach (string name in namesForEveryClassC)
            data.Add(new ClassC(name));
    }
}

public class ClassC
{
    public string name { get; set; } // This is only to identify columns
    public int value { get; set; } // Binded in the DataGridView as a cell and able to be set by the user

    public ClassC(string aName)
    {
        this.name = aName;
        this.value = 0;
    }
}

ClassB 就像 DGV 列的下一部分,静态字符串集合用作列标题的名称,也可以从 ListBox 中由用户编辑,应该绑定到每一列的是 ClassC 中的 int 值。基本上DGV应该像......

 Class A properties      namesForEveryClassC string items as headers
+-----------+-----------+--------+--------+--------+ ... +--------+
| PropertyA | PropertyB | ValueA | ValueB | ValueC | ... | ValueN |
+-----------+-----------+--------+--------+--------+ ... +--------+
|    ...    |    ...    |    2   |    4   |   0    |     |    7   |
 Class A values          int values in every ClassC from ClassB collection data

哪种方法应该好?ClassB 继承 BindingSource?使用 ITypedList 接口和 PropertyDescriptor?手动设置每一列?

我的主要问题是使用 ClassB 的索引器访问值。

标签: c#data-bindingdatagridviewnesteddatasource

解决方案


推荐阅读