如何将WPF DataGrid绑定到可变列数?我的WPF应用程序生成一组数据,每次可能有不同的列数。输出中包括将用于应用格式设置的每一列的说明。输出的简化版本可能如下所示:class Data{
IList<ColumnDescription> ColumnDescriptions { get; set; }
string[][] Rows { get; set; }}该类设置为WPF DataGrid上的DataContext,但我实际上是以编程方式创建列的:for (int i = 0; i < data.ColumnDescriptions.Count; i++){
dataGrid.Columns.Add(new DataGridTextColumn
{
Header = data.ColumnDescriptions[i].Name,
Binding = new Binding(string.Format("[{0}]", i))
});}是否有任何方法替代XAML文件中的数据绑定来替换此代码?
3 回答
PIPIONE
TA贡献1829条经验 获得超9个赞
public ObservableCollection<DataGridColumn> ColumnCollection{ get; private set;}
<DataGrid Name="dataGrid" local:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}" AutoGenerateColumns="False" ...>
public class DataGridColumnsBehavior{ public static readonly DependencyProperty BindableColumnsProperty = DependencyProperty.RegisterAttached("BindableColumns", typeof(ObservableCollection<DataGridColumn>), typeof(DataGridColumnsBehavior), new UIPropertyMetadata(null, BindableColumnsPropertyChanged)); private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { DataGrid dataGrid = source as DataGrid; ObservableCollection<DataGridColumn> columns = e.NewValue as ObservableCollection<DataGridColumn>; dataGrid.Columns.Clear(); if (columns == null) { return; } foreach (DataGridColumn column in columns) { dataGrid.Columns.Add(column); } columns.CollectionChanged += (sender, e2) => { NotifyCollectionChangedEventArgs ne = e2 as NotifyCollectionChangedEventArgs; if (ne.Action == NotifyCollectionChangedAction.Reset) { dataGrid.Columns.Clear(); foreach (DataGridColumn column in ne.NewItems) { dataGrid.Columns.Add(column); } } else if (ne.Action == NotifyCollectionChangedAction.Add) { foreach (DataGridColumn column in ne.NewItems) { dataGrid.Columns.Add(column); } } else if (ne.Action == NotifyCollectionChangedAction.Move) { dataGrid.Columns.Move(ne.OldStartingIndex, ne.NewStartingIndex); } else if (ne.Action == NotifyCollectionChangedAction.Remove) { foreach (DataGridColumn column in ne.OldItems) { dataGrid.Columns.Remove(column); } } else if (ne.Action == NotifyCollectionChangedAction.Replace) { dataGrid.Columns[ne.NewStartingIndex] = ne.NewItems[0] as DataGridColumn; } }; } public static void SetBindableColumns(DependencyObject element, ObservableCollection<DataGridColumn> value) { element.SetValue(BindableColumnsProperty, value); } public static ObservableCollection<DataGridColumn> GetBindableColumns(DependencyObject element) { return (ObservableCollection<DataGridColumn>)element.GetValue(BindableColumnsProperty); }}
- 3 回答
- 0 关注
- 1335 浏览
添加回答
举报
0/150
提交
取消