c# - WPF 使用数据/设置 ItemsSource 填充 Datagrid 的 DataGridCheckBoxColumn

标签 c# wpf datatable datagrid

我有一个带有数据网格的简单WPF应用程序,用户在其中设置日期从和日期到(日期范围),然后我以编程方式添加DataGridCheckColumns。到这里一切都正常。然后,当我想填充数据网格的 DataGridCheckColumns 时,我只是找不到数据 - 我可能设置了错误的绑定(bind)或其他东西。

这是我的代码:

ObservableCollection<List<bool>> days = new ObservableCollection<List<bool>>();
DataTable daysList = new DataTable();
List<bool> listbools = new List<bool>();
List<List<bool>> ll = new List<List<bool>>();
int c = 0;
for (DateTime d = (DateTime)DatumOd.SelectedDate; d <= (DateTime)DatumDo.SelectedDate; d = d.AddDays(1))
{
    //DataGridRooms.Columns.Add(new DataGridTextColumn() { Header = d.ToString().Substring(0,6) });
    daysList.Columns.Add(d.ToString().Substring(0, 6));
    listbools.Add(c%2 ==1?true:false);
    DataGridCheckBoxColumn dd = new DataGridCheckBoxColumn() 
    { 
        Header = d.ToString().Substring(0, 6),
        Binding = new Binding("Binding listbools, mode=TwoWay"),
        IsReadOnly = false,
        DisplayIndex = c
    };
    
    DataGridRooms.Columns.Add(dd);
    c++;
}

daysList.Rows.Add(listbools);

ll.Add(listbools);
days.Add(listbools);
//days.Add(daysList);
DataGridRooms.ItemsSource = ll;

这是我已经尝试过的(DataTable、List、ObservableCollection of List,..)。 这是现在的样子。 Right now datagrid looks like this

这就是我想要的。

Here is how it should look like

还有什么,数据网格显示额外的列容量和计数,我猜这是因为错误的 DataGridCheckBoxColumn 绑定(bind)或 DataGrid 的 ItemsSource,但我无法弄清楚。 有人能帮助我吗?谢谢。

最佳答案

使用 DataTable 应该很简单(它具有表格结构 - 列和行 - 就像 DataGrid 一样):

DataTable daysList = new DataTable();

// creating columns
for (DateTime d = new DateTime(2020, 12, 1); d <= new DateTime(2020, 12, 14); d = d.AddDays(1))
{
    string columnName = d.ToString("dd.MM");
    daysList.Columns.Add(columnName, typeof(bool));

    DataGridCheckBoxColumn dd = new DataGridCheckBoxColumn() 
    {
        Header = columnName,
        // have to use [ and ] because columnName contains a dot. It is DataTable quirk
        Binding = new Binding("[" + columnName + "]"),
    };
    
    DataGridRooms.Columns.Add(dd);
}

// creating rows with data
for(int r = 0; r < 5; r++)
{
    var row = daysList.NewRow();
    
    // filling cells in a row
    for(int c = 0; c < daysList.Columns.Count; c++)
    {
        row[c] = (c % ( r + 2)) == 0; // just an example
    }

    daysList.Rows.Add(row);
}
DataGridRooms.ItemsSource = daysList.DefaultView;

DataGrid

关于c# - WPF 使用数据/设置 ItemsSource 填充 Datagrid 的 DataGridCheckBoxColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65327871/

相关文章:

c# - c#中的数据表到XML,其中一些项目是列表<object>

jQuery DataTables 列出 JSON 数据

c# - ASP.NET Web API OData - 将 DTO 查询转换为实体查询

c# - 对数字中的数字求和的最快方法

c# - 如何在 C# 中连接两个数组?

c# - 如何找出托管了哪些 wcf 服务

c# - 处理异常后发生未处理的异常

c# - 如果有新项目到达,则中断当前项目的处理

c# - 有没有办法从表单关闭事件中的所有绑定(bind)元素中删除绑定(bind)?

c# - 将 Excel 数据导入 C# 而第一行不成为列名?