How do I bind a WPF DataGrid to a variable number of columns?

后端 未结 8 1411
逝去的感伤
逝去的感伤 2020-11-22 10:29

My WPF application generates sets of data which may have a different number of columns each time. Included in the output is a description of each column that will be used t

相关标签:
8条回答
  • 2020-11-22 11:08

    There is a sample of the way I do programmatically:

    public partial class UserControlWithComboBoxColumnDataGrid : UserControl
    {
        private Dictionary<int, string> _Dictionary;
        private ObservableCollection<MyItem> _MyItems;
        public UserControlWithComboBoxColumnDataGrid() {
          _Dictionary = new Dictionary<int, string>();
          _Dictionary.Add(1,"A");
          _Dictionary.Add(2,"B");
          _MyItems = new ObservableCollection<MyItem>();
          dataGridMyItems.AutoGeneratingColumn += DataGridMyItems_AutoGeneratingColumn;
          dataGridMyItems.ItemsSource = _MyItems;
    
        }
    private void DataGridMyItems_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
            {
                var desc = e.PropertyDescriptor as PropertyDescriptor;
                var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;
                if (att != null)
                {
                    if (att.Name == "My Combobox Item") {
                        var comboBoxColumn =  new DataGridComboBoxColumn {
                            DisplayMemberPath = "Value",
                            SelectedValuePath = "Key",
                            ItemsSource = _ApprovalTypes,
                            SelectedValueBinding =  new Binding( "Bazinga"),   
                        };
                        e.Column = comboBoxColumn;
                    }
    
                }
            }
    
    }
    public class MyItem {
        public string Name{get;set;}
        [ColumnName("My Combobox Item")]
        public int Bazinga {get;set;}
    }
    
      public class ColumnNameAttribute : Attribute
        {
            public string Name { get; set; }
            public ColumnNameAttribute(string name) { Name = name; }
    }
    
    0 讨论(0)
  • 2020-11-22 11:11

    I have found a blog article by Deborah Kurata with a nice trick how to show variable number of columns in a DataGrid:

    Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM

    Basically, she creates a DataGridTemplateColumn and puts ItemsControl inside that displays multiple columns.

    0 讨论(0)
提交回复
热议问题