我想在我们的应用程序中创建一个如下所示的DataGrid:
|Name|Email |OC |Path|01.01.17|05.08.17|... (more dates and checkboxes)
|Foo |foo@bar.com|...|... |[x] | |...
|Bar |bar@bar.com|...|... |[ ] |[x] |...
|Foo |foo@bar.com|...|... | |[ ] |...
正如您所看到的,列数必须是动态的,复选框列可以包含复选框,也可以不包含任何内容。 我的方法是使用转换器来构建我的DataTable。
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var techWithDates = (TechFvo[])value;
var dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Name"));
dataTable.Columns.Add(new DataColumn("Email"));
dataTable.Columns.Add(new DataColumn("OC"));
dataTable.Columns.Add(new DataColumn("Path"));
if (techWithDates == null)
return dataTable.DefaultView;
var days = GetFormattedDays(techWithDates);
foreach (var day in days)
dataTable.Columns.Add(new DataColumn(day, typeof(bool)));
dataTable.Rows.Add(dataTable.NewRow());
foreach (var tech in techWithDates)
{
if (tech.GetTerminListe().Count == 0)
continue;
var dataRow = dataTable.NewRow();
dataRow[0] = tech.Name;
dataRow[1] = tech.EMail;
dataRow[2] = string.IsNullOrWhiteSpace(tech.Path) ? "No" : "Yes";
dataRow[3] = tech.Path;
AddTechCols(dataRow, tech, days);
dataTable.Rows.Add(dataRow);
}
return dataTable.DefaultView;
}
private void AddTechCols(DataRow row, TechFvo techs, List<string> aDays)
{
var dates = techs.GetTerminListe();
var datesAsStrList = new List<string>();
foreach (var date in dates)
{
var thisStr = DateToString(date.Day);
if (!datesAsStrList.Contains(thisStr))
datesAsStrList.Add(thisStr);
}
foreach (var aDay in aDays)
{
if (datesAsStrList.Contains(aDay))
row[aDay] = true;
else
row[aDay] = DBNull.Value;
}
}
这样可行,但每行的每个复选框列都有复选框。 在构建行时,如何隐藏列中的复选框?
我试过
row[aDay] = false;
row[aDay] = null;
row[aDay] = DbNull.Value();
但没有任何效果...... 谢谢!
答案 0 :(得分:0)
您可以拦截创建DatagridCheckBoxColumns的时刻并更改CheckBoxes设置。
添加事件处理程序DataGrid.AutoGeneratingColumn
事件
<DataGrid AutoGeneratingColumn="DataGrid_OnAutoGeneratingColumn">
</DataGrid>
// fixing checkboxes in DataGrid DataGridCheckBoxColumns
private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
var column = e.Column as DataGridCheckBoxColumn;
if (column == null)
return;
var dg = sender as DataGrid;
if (dg == null)
return;
column.ElementStyle = (Style)dg.FindResource("DateChk");
column.EditingElementStyle = (Style)dg.FindResource("DateChk");
}
“DateChk”是CheckBox样式,在参考资料中声明,当值为null
(或DataTable中的DBNull.Value
时)使CheckBox隐藏和禁用
<Style x:Key="DateChk" TargetType="CheckBox">
<Style.Triggers>
<Trigger Property="IsChecked" Value="{x:Null}">
<Setter Property="Visibility" Value="Hidden"/>
<Setter Property="IsEnabled" Value="False"/>
</Trigger>
</Style.Triggers>
</Style>