I have a WPF form with a DataGrid. New columns can be added to the datagrid manually by the user via a button. This is the code to add a new column:
private void ColumnAdornerAddButton_MouseDown(object sender, MouseButtonEventArgs e) { DataGridTextAdornerColumn column = new DataGridTextAdornerColumn(); column.Header = "New column"; column.HeaderStyle = (Style)FindResource("columnHeader"); column.AdornerTemplate = (DataTemplate)FindResource("columnAdorner"); Binding binding = new Binding("Data"); binding.Mode = BindingMode.TwoWay; column.Binding = binding; grid.Columns.Insert(grid.Columns.Count - 1, column); //Add adorner DataGridColumnHeader header = GetColumnHeaderFromColumn(column); AddAdorner(header, column.AdornerTemplate, column.IsReadOnly); } private DataGridColumnHeader GetColumnHeaderFromColumn(DataGridColumn column) { // dataGrid is the name of your DataGrid. In this case Name="dataGrid" List<DataGridColumnHeader> columnHeaders = GetVisualChildCollection<DataGridColumnHeader>(grid); foreach (DataGridColumnHeader columnHeader in columnHeaders) { if (columnHeader.Column == column) { return columnHeader; } } return null; }
The problem is that after adding a column to the grid, its header has not yet been generated and it is not in the visual tree. Thus, I cannot get the header for the new column and apply adorner to it. I tried calling the recursive ApplyTemplate method on the visual grid tree without knowing.
Is there a way to get the grid to generate a DataGridColumnHeader for a new column in the code?
Thanks in advance.
source share