DataGrid以编程方式绑定

时间:2014-11-10 21:23:40

标签: c# wpf datagrid

有没有办法以编程方式创建数据绑定到DataGrid,因此在这样的绑定方法中,我接收每行中的项目,并随意访问项目中的数据。

例如,

class Addition
{
    public int P1 {get;set;}
    public int P2 {get;set;}
}

在我的DataGrid中,我希望有一个其他列,在这个例子中输出它们的总和。

在我真正的问题中,这变得更加严重,数据是动态的,我甚至无法预见列的数量和标题(真实数据代表一行作为字典)。

数据可视为只读。


更新

也许更好的例子,我想要实现的目标将有助于你和我。

我这里有一系列字典。

Dictionary<string, int>[] data;

在同一个数组中给出两个字典,它们必须具有相同的密钥集。

所以说,在这样的数组中,键集是{"P1", "P2"}

但另一个阵列来了,

Dictionary<string, int>[] data2;

在此数组中,键集为{"P1", "P2", "P3"}

所以我必须在这里做,就是拥有一个DataGrid,调整所有的键集,并有另一列,值是sum-them-all。

此问题示例显示与我的真实问题相同的本质。

2 个答案:

答案 0 :(得分:0)

实际上,我不确定数据网格视图是否适合您的情况,但它可以自定义,您可以动态完全控制它。

你可以修改类,添加一个数据成员来添加P1和P2,然后使你dataGridView的数据源是这个类的列表

class Addition
{
    public int P1 {get;set;}
    public int P2 {get;set;}
    public long varSum {get;set;}

    public void Addition (int P1, int P2)
    {
        this.P1 = P1; 
        this.P2 = P2;
        this.varSum = P1 + P2;
    }
}

然后

Addition add1 = new Addition (1,2);
List <Addition> addList = new List <Addition> ();
addList.insert(add1);
// you need to define dgv as a DataGridVirw
dgv.dataSource = addList;

然后您的数据网格视图将有三列,P1,P2及其总和(varSum)。

答案 1 :(得分:-1)

那么,数据网格数据视图源可以是字符串数组的列表,其中每个单个DGV行是字符串数组(例如{“1”,“2”,“3”})。然后,您可以将字典转换为每个DGV行的字符串数组,然后构建这些数组的列表,并将每行分别添加到DGV。

int n = 10;/* retrieve this value from your dictionary as your columns count*/;
string [] xx = new string[n];

dataGridView1.ColumnCount = n; 
for (int j = 0; j < n; j++)
{
    xx[j]=("0"); // fill from your dictionary
    dataGridView1.Columns[j].HeaderText = "someColHeaderText";                    
}

int m = 10;/* retrieve this value from your dictionary as your rows count*/;
for (int i = 0; i < m; i++)
{        
     dataGridView1.Rows.Add(xx);
     dataGridView1.Rows[i].HeaderCell.Value = "someRowHeaderText";
}