WPF DataGrid: Dynamically bind the number of columns
Question:
A WPF application generates a dataset with a variable number of columns, the required column descriptions are included in the output. The code for programmatically creating columns involves binding using string formatting, for example:
<code class="language-csharp">dataGrid.Columns.Add(new DataGridTextColumn { Header = data.ColumnDescriptions[i].Name, Binding = new Binding(string.Format("[{0}]", i)) });</code>
The goal is to replace this code with data binding in the XAML file.
Solution:
The Columns property of DataGrid is read-only and cannot be bound directly. However, an additional property called BindableColumns can be used as a workaround:
<code class="language-csharp">public class DataGridColumnsBehavior { // 附加属性,绑定到DataGridColumn集合 public static readonly DependencyProperty BindableColumnsProperty = DependencyProperty.RegisterAttached("BindableColumns", typeof(ObservableCollection<DataGridColumn>), typeof(DataGridColumnsBehavior), new UIPropertyMetadata(null, BindableColumnsPropertyChanged)); }</code>
In the XAML file, bind the BindableColumns property to the column collection:
<code class="language-xml"><DataGrid ... AutoGenerateColumns="False" local:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}" Name="dataGrid"></DataGrid></code>
<code class="language-csharp">public ObservableCollection<DataGridColumn> ColumnCollection { get; private set; }</code>
The BindableColumnsPropertyChanged method updates the Columns property when the bound collection changes:
<code class="language-csharp">private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { DataGrid dataGrid = source as DataGrid; // 获取DataGrid实例 // 清除现有列 dataGrid.Columns.Clear(); ObservableCollection<DataGridColumn> columns = e.NewValue as ObservableCollection<DataGridColumn>; if (columns == null) { return; } // 添加新列 foreach (DataGridColumn column in columns) { dataGrid.Columns.Add(column); } // 处理集合更改 columns.CollectionChanged += (sender, e2) => { // ... 处理集合变化,例如重新绑定列 dataGrid.Columns.Clear(); foreach (DataGridColumn column in columns) { dataGrid.Columns.Add(column); } }; }</code>
This method listens for collection changes (add, delete, replace) and updates the Columns property accordingly. It should be noted that in the BindableColumnsPropertyChanged
method, the acquisition of the dataGrid
instance is added, and the collection change event is more completely processed to ensure that column updates are synchronized.
The above is the detailed content of How to Bind a Dynamic Number of Columns to a WPF DataGrid?. For more information, please follow other related articles on the PHP Chinese website!