0
votes

I am trying to create custom columns with a label and a combobox for the column headers. The first time the grid is loaded properly. On the click of the button, I change the itmesources of the Datagrid. I see the cells of the datagrid getting updated, but not the headers. I also see that the Datagrid_Loaded is not being called. On debugging I found that for "Binding" object I supply the binding path, but for header I supply the source, hence the header don't get updated. How to supply path for the header so that its is similar to that of Binding?

private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
    DataGrid grid = sender as DataGrid;
    if (grid.Items.Count == 0)
    {
        return;
    }
   StageVM data = grid.Items[0] as StageVM;
    if (data == null)
    {
        return;
    }
    int index = 0;
    foreach (StageItemVM param in data.Stage)
    {
        var binding = new Binding(string.Format("Stage[{0}].StageItem.Value", index));
        grid.Columns.Add(new CustomBoundColumn()
        {
            CanUserSort = false,
            HeaderTemplateSelector = this.FindResource("ColumnHeaderTemplateSelector") as  DataTemplateSelector,
            HeaderStyle = this.FindResource("StageHeaderStyle") as Style,
            Header = (new Binding().Source = param.StageItem.Key),
            Binding = binding,
            TemplateSelectorName = "StageRangeColumnTemplateSelector"
        });
        index++;
    }
}

And the customBoundColumn class is as follows:

 public class CustomBoundColumn : DataGridBoundColumn
{
     public string TemplateSelectorName { get; set; }
     protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
         var binding = new Binding(((Binding)Binding).Path.Path);
         binding.Source = dataItem;
         var content = new ContentControl();
         content.ContentTemplateSelector =(DataTemplateSelector)cell.FindResource(TemplateSelectorName);
        content.SetBinding(ContentControl.ContentProperty, binding);
       return content;
    }
    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
   {
       return GenerateElement(cell, dataItem);
    }
}
1

1 Answers

0
votes

Check if this can help you: WPF DataGridTextColumn header binding

I had the same problem about binding datagrid headers with my ViewModel. It's a xaml based solution.