C# 如何在代码中设置 DataGridTextColumn 的绑定?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/916454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set the binding of a DataGridTextColumn in code?
提问by Edward Tanguay
I'm using the toolkit:DataGrid from CodePlex.
我正在使用 CodePlex 的工具包:DataGrid。
I'm generating the columns in code.
我在代码中生成列。
How can I set the equivalent of {Binding FirstName}in code?
如何在代码中设置{Binding FirstName}的等效项?
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.
或者,我怎么能只设置 value,这就是我需要做的,不一定绑定它。我只想要数据网格中单元格中模型属性的值。
DataGridTextColumn dgtc = new DataGridTextColumn();
dgtc.Header = smartFormField.Label;
dgtc.Binding = BindingBase.Path = "FirstName"; //PSEUDO-CODE
dgtc.CellValue= "Jim"; //PSEUDO-CODE
CodePlexDataGrid.Columns.Add(dgtc);
采纳答案by samjudson
Untested, but the following should work:
未经测试,但以下应该工作:
dgtc.Binding = new Binding("FirstName");
回答by Aby
Example:
例子:
DataGridTextColumn dataColumn = new DataGridTextColumn();
dataColumn.Header = "HeaderName";
dataColumn.Binding = new Binding("HeaderBind");
dataGrid.Columns.Add(dataColumn);
回答by Christian
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:
关于新绑定的第一个答案对我来说也是正确的。使用该答案的主要问题是 Binding 属于四个命名空间 8-(。正确的命名空间是 System.Windows.Data (.NET 4, VS2010)。这导致了一个更完整的答案:
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:
在我的情况下,设置绑定的上下文是对 DataGrid 列的迭代。在可以更改绑定之前,必须将基类 DataGridColumn 强制转换为 DataGridTextColumn。然后可以更改绑定:
int pos = 0;
var dgtc = dataGrid.Columns[pos] as DataGridTextColumn;
dgtc.Binding = new System.Windows.Data.Binding("FirstName");