如何在代码中设置DataGridTextColumn的绑定?

13
我正在使用来自CodePlex的toolkit:DataGrid。
我正在代码中生成列。
如何在代码中设置等效于{Binding FirstName}的内容?
或者,我该如何只是设置这个值,我只需要把我的模型属性值放在datagrid的单元格中,而不一定要进行绑定。
DataGridTextColumn dgtc = new DataGridTextColumn();
dgtc.Header = smartFormField.Label;
dgtc.Binding = BindingBase.Path = "FirstName"; //PSEUDO-CODE
dgtc.CellValue= "Jim"; //PSEUDO-CODE
CodePlexDataGrid.Columns.Add(dgtc);
3个回答

23

未经过测试,但以下代码应该可以正常工作:

dgtc.Binding = new Binding("FirstName");

6

对于我来说,关于新的Binding的第一个答案是正确的。使用该答案的主要问题是Binding属于四个命名空间,这导致正确的命名空间是System.Windows.Data(.NET 4,VS2010)。这将导致更完整的答案:

dgtc.Binding = new System.Windows.Data.Binding("FirstName");

一点小注:

在我的情况下,设置绑定的上下文是在DataGrid的列迭代过程中。在更改绑定之前,需要将基类DataGridColumn强制转换为DataGridTextColumn。然后就可以更改绑定了:

int pos = 0;
var dgtc = dataGrid.Columns[pos] as DataGridTextColumn;
dgtc.Binding = new System.Windows.Data.Binding("FirstName");

2

例子:

DataGridTextColumn dataColumn = new DataGridTextColumn();
dataColumn.Header = "HeaderName";
dataColumn.Binding = new Binding("HeaderBind");
dataGrid.Columns.Add(dataColumn); 

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