我有一个带有数据网格的简单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,..)。 这是现在的样子。
这就是我想要的。
还有什么,数据网格显示额外的列容量和计数,我猜这是因为错误的 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;
关于c# - WPF 使用数据/设置 ItemsSource 填充 Datagrid 的 DataGridCheckBoxColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65327871/