Reputation: 321
I'm trying to add columns to my DataGrid programmatically as they're not known until run-time. I've got most of the way there and adding a "normal" column from the code behind isn't a problem. However the column I'm trying to add now has a DataTemplate. Here's the XAML:
<DataGridTemplateColumn Header="{Binding colHeader}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border BorderBrush="{Binding BorderColour}" BorderThickness="2">
<TextBlock Text="{Binding TextInfo}" />
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Normally I'd use something like this to create a column to add to the grid:
Private Function AddColumn(colHeader As String, colBinding As String) As DataGridColumn
Dim textColumn As New DataGridTextColumn()
textColumn.Header = colHeader
textColumn.Binding = New Binding(colBinding)
Return textColumn
End Sub
But I'm stumped as to how to add the more complex XAML. Any suggestions?
Thanks for any help!
Upvotes: 3
Views: 5777
Reputation: 176
Refer link: http://blogs.msdn.com/b/scmorris/archive/2008/04/14/defining-silverlight-datagrid-columns-at-runtime.aspx
Code snippet is from above link:(this is one way of doing that.Otherway is also explained in that link)
Xaml:
<UserControl.Resources>
<local:DateTimeConverter x:Key="DateConverter" />
<DataTemplate x:Key="myCellTemplate">
<TextBlock
Text="{Binding Birthday,
Converter={StaticResource DateConverter}}"
Margin="4"/>
</DataTemplate>
<DataTemplate x:Key="myCellEditingTemplate">
<basics:DatePicker
SelectedDate="{Binding Birthday, Mode=TwoWay}" />
</DataTemplate>
Code Behind:
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = "Birthday";
templateColumn.CellTemplate = (DataTemplate)Resources["myCellTemplate"];
templateColumn.CellEditingTemplate =
(DataTemplate)Resources["myCellEditingTemplate"];
targetDataGrid.Columns.Add(templateColumn);
Upvotes: 0
Reputation: 4659
Define the DataTemplate of your column in a resource dictionary with a x:Key
property then access it in your code behind to set your cell template.
<DataTemplate x:Key="your_data_template">
<Border BorderBrush="{Binding BorderColour}" BorderThickness="2">
<TextBlock Text="{Binding TextInfo}" />
</Border>
</DataTemplate>
Then in the code behind
textColumn.CellTemplate = Application.Current.FindResource("your_data_template") as DataTemplate
Upvotes: 5