How to get DataGrid to rebuild VisualTree for its columns

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.

0
source share
2 answers

Hello, after adding columns to the datagrid, call the UpdateLayOut () DataGrid method.

 datagrid.UpdateLayout(); 

Hope this helps.

+1
source

I just want to improve the solution, datagrid.Items.Refresh(); Method datagrid.Items.Refresh(); help recreate the view (Datagrid). this way you can see the updated value in the datagrid

0
source

Source: https://habr.com/ru/post/1211013/


All Articles