如何在 DataGrid 控件中包含列表框
本文关键字:包含 列表 控件 DataGrid | 更新日期: 2023-09-27 18:31:21
我正在使用MVVM模式开发WPF 4应用程序。我有一个 DataGrid 控件,其中的列自动生成并与 DataTable 对象绑定。
我现在的表格是这样的:
+------------+---------------+---------------+
| Date | Shop 1 | Shop 2 |
+------------+---------------+---------------+
| 2016-01-01 | 09:00 - 13:00 | N/A |
+------------+---------------+---------------+
| 2016-01-02 | N/A | 14:00 - 18:00 |
+------------+---------------+---------------+
我需要这个结果:
+------------+---------------+---------------+
| Date | Shop 1 | Shop 2 |
+------------+---------------+---------------+
| 2016-01-01 | 9:00 - 13:00 | N/A |
| | 14:00 - 18:00 | |
+------------+---------------+---------------+
| 2016-01-02 | | 14:00 - 18:00 |
| | 9:00 - 10:00 | |
| | 12:00 - 14:00 | |
+------------+---------------+---------------+
对于每个小时范围,我需要不同的颜色,因此我将为表的每个单元格绑定一个列表框。
实际上我的 XAML 代码是这样的:
<DataGrid x:Name="grdScheduler"
IsEnabled="False"
AutoGenerateColumns="True"
HeadersVisibility="None"
ItemsSource="{Binding SchedulerDataTable, Mode=OneWay}">
</DataGrid>
拜托,你能帮我吗?
谢谢
我认为这与您所问的相似。但我举了一个适合你问题的例子。
您需要提供List<object>
列类型的DataGridtemplateColumn
。为此,我们为 Datagrid 的 AutoGeneratingColumn 事件创建一个事件处理程序。是的,您需要在后面编写一些代码,但这不会破坏 MVVM 世界中的任何内容。您可以编写隐藏代码,也可以实现自己的 datagrid 自定义控件(如果需要更简洁的方法)。现在在DataGrid.Resource中,我们有一个名为ListTemplate的数据模板。这将是每List<object>
列的单元格模板。
<DataGrid x:Name="grdScheduler"
IsEnabled="False"
AutoGenerateColumns="True"
HeadersVisibility="None"
ItemsSource="{Binding SchedulerDataTable, Mode=OneWay}"
AutoGeneratingColumn="grdScheduler_AutoGeneratingColumn">
<DataGrid.Resources>
<DataTemplate x:Key="ListTemplate">
<ListBox ItemsSource="{Binding}" />
</DataTemplate>
</DataGrid.Resources>
</DataGrid>
对于类型为 List<object>
的每一列,您需要使用 DynamicDataGridTemplateColumn,并将 ListTemplate 用作 CellTemplate。在此代码块中,如果需要,还可以对生成的每个列使用不同的模板。
private void grdScheduler_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(List<object>))
{
DynamicDataGridTemplateColumn dgTemplateCol = new DynamicDataGridTemplateColumn();
dgTemplateCol.CellTemplate = (sender as DataGrid).FindResource("ListTemplate") as DataTemplate;
dgTemplateCol.ColumnName = e.PropertyName;
e.Column = dgTemplateCol;
}
}
这是DynamicDataGridTemplateColumn的代码。
public class DynamicDataGridTemplateColumn : DataGridTemplateColumn
{
public string ColumnName
{
get;
set;
}
protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
// The DataGridTemplateColumn uses ContentPresenter with your DataTemplate.
ContentPresenter cp = (ContentPresenter)base.GenerateElement(cell, dataItem);
// Reset the Binding to the specific column. The default binding is to the DataRowView.
BindingOperations.SetBinding(cp, ContentPresenter.ContentProperty, new Binding(this.ColumnName));
return cp;
}
}