How to create a DataGridTemplateColumn at runtime with binding?

Nov 5, 2008 at 7:30 PM
Hi,
Creating and Binding at runtime or code behind is possible with DatGridColumn together with DatGridBoundColumn.
I would like to create and bind to a DataGridTemplateColumn at runtime or code behind.
The control I want to bind to is a DatePicker.

Please help.
WorstCase
Coordinator
Nov 5, 2008 at 8:34 PM
Here is an example:

DataGridTemplateColumn

 

templateColumn = new DataGridTemplateColumn();
templateColumn.Header =
"Date";

DataTemplate cellTemplate = new DataTemplate();
FrameworkElementFactory cellTemplateFactory = new FrameworkElementFactory(typeof(TextBlock));
Binding binding = new Binding("Date");
binding.StringFormat =
"d";
cellTemplateFactory.SetBinding(
TextBlock.TextProperty, binding);
cellTemplate.VisualTree = cellTemplateFactory;
cellTemplate.Seal();
templateColumn.CellTemplate = cellTemplate;

DataTemplate cellEditingTemplate = new DataTemplate();
FrameworkElementFactory cellEditingTemplateFactory = new FrameworkElementFactory(typeof(DatePicker));
Binding binding2 = new Binding("Date");
binding2.Mode =
BindingMode.TwoWay;
binding2.UpdateSourceTrigger =
UpdateSourceTrigger.PropertyChanged;
cellEditingTemplateFactory.SetBinding(
DatePicker.SelectedDateProperty, binding2);
cellEditingTemplate.VisualTree = cellEditingTemplateFactory;
cellEditingTemplate.Seal();
templateColumn.CellEditingTemplate = cellEditingTemplate;

DataGrid_Standard.Columns.Add(templateColumn);

 

Nov 5, 2008 at 9:50 PM
Thank you very much, Vinsibal.
Now it is working as exspected. I don't use the TextBox CellTemplate so I see the DatePicker directly. Should I use that TextBox CellTemplate anyway?

Still some problems with DataGrid.RowValidationRules.
Will read some more samples of your blog first before asking for that again.
Thank you.
WorstCase
Coordinator
Nov 6, 2008 at 1:02 PM
You don't have to use a TextBlock.  It is up to you.