wpf datagrid dynamic columns
时间: 2023-09-12 16:10:46 浏览: 47
WPF DataGrid allows you to dynamically add or remove columns at runtime based on your data source. Here are the steps to create dynamic columns in WPF DataGrid:
1. Create a class that represents your data model. This class should have properties for each column you want to display in the DataGrid.
2. Create an ObservableCollection of your data model class. This collection will be used as the ItemsSource for the DataGrid.
3. Create a DataGrid control in your XAML file and set the ItemsSource property to the ObservableCollection.
4. In the code-behind file, create a method that adds or removes columns from the DataGrid. This method should take a parameter that specifies the name of the column to add or remove.
5. To add a column, create a DataGridTextColumn object and set its Header and Binding properties to the column name and property name, respectively. Then add the column to the DataGrid.Columns collection.
6. To remove a column, find the DataGridColumn object with the specified name in the DataGrid.Columns collection and remove it.
7. Call the method to add or remove columns as needed.
Here's an example of how to add a column dynamically:
```csharp
private void AddColumn(string columnName)
{
var column = new DataGridTextColumn();
column.Header = columnName;
column.Binding = new Binding(columnName);
dataGrid.Columns.Add(column);
}
```
And here's how to remove a column dynamically:
```csharp
private void RemoveColumn(string columnName)
{
var column = dataGrid.Columns.FirstOrDefault(c => c.Header.ToString() == columnName);
if (column != null)
{
dataGrid.Columns.Remove(column);
}
}
```