0
votes

I'm dynamically creating DataGrid columns (based on an event from my ViewModel) and programmatically adding them to an existing DataGrid. Each column uses a generic HeaderTemplate by setting it to a DataTemplate that has been identified in the xaml. The DataTemplate contains two labels in which needs their content needs to be changed upon creation of the DataGrid column. How would this be done? I understand that the DataTemplate uses the ContentPresenter but I am having trouble accessing it within a dynamically created DataGrid column. Code is as follows:

xaml: (template used to format the DataGrid column header):

    <DataTemplate x:Key="columnTemplate">
        <StackPanel>
            <Label Padding="0" Name="labelA"/>
            <Separator HorizontalAlignment="Stretch"/>
            <Label Padding="0" Name="labelB"/>
        </StackPanel>
    </DataTemplate>

c#: (used to dynamically create a DataGrid column and add it to an existing DataGrid)

            var dataTemplate = FindResource("columnTemplate") as DataTemplate;
            var column = new DataGridTextColumn();

            column.HeaderTemplate = dataTemplate;
            DataGrid1.Columns.Add(column);

I would like to then access both labelA and labelB and change the content.

1

1 Answers

1
votes

You can't change the contents of a template at runtime unless you want every item which uses that template to have it's contents changed as well.

In your situation, I would just create the header as needed. You can make it easier by putting the code to create the Header in it's own method.

public void AddColumnHeader(DataGridTextColumn column, string header1, string header2)
{
    var panel = new StackPanel();

    var labelA = new Label();
    labelA.Content = header1;
    panel.Children.Add(labelA);

    var separator = new Separator();
    separator.HorizontalAlignment = HorizontalAlignment.Stretch;
    panel.Children.Add(separator);

    var labelB = new Label();
    labelB.Content = header2;
    panel.Children.Add(labelB);

    column.Header = panel;
}

Then to apply your header, just use

var column = new DataGridTextColumn();
AddColumnHeader(column);
DataGrid1.Columns.Add(column, "label content 1", "label content 2");