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

后端 未结 8 1512
逝去的感伤
逝去的感伤 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 10:56

    You can create a usercontrol with the grid definition and define 'child' controls with varied column definitions in xaml. The parent needs a dependency property for columns and a method for loading the columns:

    Parent:


    public ObservableCollection gridColumns
    {
      get
      {
        return (ObservableCollection)GetValue(ColumnsProperty);
      }
      set
      {
        SetValue(ColumnsProperty, value);
      }
    }
    public static readonly DependencyProperty ColumnsProperty =
      DependencyProperty.Register("gridColumns",
      typeof(ObservableCollection),
      typeof(parentControl),
      new PropertyMetadata(new ObservableCollection()));
    
    public void LoadGrid()
    {
      if (gridColumns.Count > 0)
        myGrid.Columns.Clear();
    
      foreach (DataGridColumn c in gridColumns)
      {
        myGrid.Columns.Add(c);
      }
    }
    

    Child Xaml:


               
      
        
        
        
    
    

    And finally, the tricky part is finding where to call 'LoadGrid'.
    I am struggling with this but got things to work by calling after InitalizeComponent in my window constructor (childGrid is x:name in window.xaml):

    childGrid.deGrid.LoadGrid();
    

    Related blog entry

提交回复
热议问题