简体   繁体   中英

Wpf DataGrid Set Columns dynamically by list property

I have a small caliburn micro MVVM project with a DataGrid. The columns will consist of x amount of 'setup's and the rows will consist of 'CustomRow'. I would like to use a ObservableCollection where CustomRow has a function property and a collection of setup property. For each setup in this collection a column should exist with the value of setup.

class CustomRow
{
    public string Function { get; set; }
    public ObservableCollection<Setup> Setups { get; set; }
}

// example class
class Setup
{
    public string Name { get; set; }
    public object Content { get; set; }
}

So I need to be able to add columns and rows dynamically depending on the itemssource (all the Setups collections will have the same size).

My problem is that I don't know how to translate the Setups property into multiple columns. I have spend quit some time on what should be a mundane problem in my opinion. But I am missing something. Any help is much appreciated.

Bind or set the ItemsSource to the ObservableCollection<CustomRow> and then get the Setups property of the first CustomRow in the source collection in the view, eg:

private void Window_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    var vm = DataContext as YourViewModel;
    dataGrid.Columns.Clear();
    if (vm.Rows != null && vm.Rows.Count > 0)
    {
        var setups = vm.Rows[0].Setups;
        foreach (var setup in setups)
        {
            dataGrid.Columns.Add(new DataGridTextColumn { Header = setup.Name, Binding = new Binding("Content ") });
        }
    }
    dataGrid.ItemsSource = vm.Rows;
}

There is no way to bind the Columns property of the DataGrid directly to a source property so you need to create the columns yourself one way or another.

You should do this in the view, in the control or in an attached behaviour that is attached to either of them. A view model should not create any columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM