【问题标题】:WPF Populating Datagrid's DataGridCheckBoxColumn with data / setting ItemsSourceWPF 使用数据/设置 ItemsSource 填充 Datagrid 的 DataGridCheckBoxColumn
【发布时间】:2020-12-16 17:06:50
【问题描述】:

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

这是我的代码:

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,..)。 这是它现在的样子。

这就是我想要的。

还有什么,datagrid显示了额外的列Capacity和Count,我猜是因为错误的DataGridCheckBoxColumn的绑定或DataGrid的ItemsSource,但我想不通。 有人能帮助我吗?谢谢。

【问题讨论】:

    标签: c# wpf datatable datagrid


    【解决方案1】:

    使用 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;
    

    【讨论】:

    • 啊,现在是它的 populatin dat,但是即使我只是复制 + 过去的代码,datagrid 也会显示重复的列但不会填充。这是否意味着我还有其他问题?老实说,你刚刚拯救了我的睡眠。非常感谢!顺便说一句,在找出下一个错误后,我会接受并投票赞成你的答案。
    • 在设置 ItemsSource 之前尝试DataGridRooms.AutoGenerateColumns=false;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    相关资源
    最近更新 更多