我已经坚持了好几天了,就是找不到自己的解决方案。我正在尝试用 List<Plants>
填充 DataGrid作为 ItemsSource。问题是,类型 Plant
有一个 ICollection<PlantType>
类型的成员为此,我需要在 DataGrid 的相应列中显示为字符串,其中 ICollection 中的每个项目都在一个新行上,如下所示:
"Type1, \n Type2, \n ..."
我将在这里展示简化的代码(复制整个代码会有点过头)。
public partial class Plants
{
public Plants()
{
PlantType = new HashSet<PlantType>();
}
public int ID { get; set; }
public string Name { get; set; }
public int Page { get; set; }
public virtual ICollection<PlantType> PlantType { get; set; }
}
请注意 PlantType
有 Type
列(不是 Plant
)。现在我想用这些信息填充 DataGrid,理想情况下它看起来像这样:
-----------------------------------------
| Name | Page | Type |
|---------------------------------------|
| plant1 | 3 | supporting |
|---------------------------------------|
| pla2 | 13 | not-supporting |
|---------------------------------------|
| | | test |
|---------------------------------------|
| | | also this type |
|---------------------------------------|
| | | type |
|---------------------------------------|
| plantZ | 40 | test |
-----------------------------------------
目前的问题是,它只填写名称和页面(因为它们不是 HashSet,因此很清楚)。这是我填充 DataGrid 的代码的样子:
private void BuildDataGridContent(List<Plants> lList)
{
dataGrid.IsReadOnly = true;
dataGrid.AutoGenerateColumns = false;
dataGrid.ItemsSource = lList;
DataGridTextColumn textColumn1 = new DataGridTextColumn();
DataGridTextColumn textColumn2 = new DataGridTextColumn();
DataGridTextColumn textColumn3 = new DataGridTextColumn();
textColumn1.Header = "Name";
textColumn1.Binding = new Binding("Name");
textColumn2.Header = "Page";
textColumn2.Binding = new Binding("Page");
textColumn3.Header = "Type";
textColumn3.Binding = new Binding("Type"); // <-- the problem is here. It can't directly access lList.PlantType.Type (PlantType = Table name; Type = column name in the SQL DB)
dataGrid.Columns.Add(textColumn1);
dataGrid.Columns.Add(textColumn2);
dataGrid.Columns.Add(textColumn3);
}
我已经尝试过一些东西,但已经用完了想法和谷歌搜索词。谁能告诉我如何正确绑定(bind) Type
以这种方式进入专栏?
最佳答案
一个相当简单的解决方案可能是引入一个 PlantViewModel
类型来绑定(bind)到每个 DataGrid 行,而不是直接绑定(bind)到您的数据模型类型 (Plant
)。这当然需要在 View 模型中重新定义一些属性,这些属性也在数据模型中加上引入从 Plant
到 PlantViewModel
的映射逻辑,并且可能反过来(如果您的 View 是可编辑的)但它促进了数据模型和 View 之间的松散耦合。
关于C# DataGrid 填充了多层列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40960444/