Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid programmatically add complex columns

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!

like image 441
qu1ckdry Avatar asked Jun 19 '26 13:06

qu1ckdry


1 Answers

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
like image 133
Sisyphe Avatar answered Jun 21 '26 04:06

Sisyphe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!