Edward Tanguay
Edward Tanguay

Reputation: 193312

How can I set the binding of a DataGridTextColumn in code?

I'm using the toolkit:DataGrid from CodePlex.

I'm generating the columns in code.

How can I set the equivalent of {Binding FirstName} in code?

Or alternatively, how can I just set the value, that's all I need to do, not necessarily bind it. I just want the value from my model property in the cell in the 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);

Upvotes: 12

Views: 21425

Answers (3)

Aby
Aby

Reputation: 21

Example:

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

Upvotes: 2

Christian
Christian

Reputation: 1027

The first answer about the new Binding is correct for me, too. The main problem to use that answer was that Binding belongs to four namespaces 8-(. The correct namespace is System.Windows.Data (.NET 4, VS2010). This leads to a more complete answer:

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

A side note:

In my case the context to set the binding was the iteration over the columns of the DataGrid. Before it is possible to change the binding it is necessary to cast the base class DataGridColumn to DataGridTextColumn. Then it is possible to change the binding:

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

Upvotes: 6

samjudson
samjudson

Reputation: 56853

Untested, but the following should work:

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

Upvotes: 22

Related Questions