我一直坚持这几天,只是无法自己找到解决方案。我想用一个List<Plants>
作为ItemsSource填充DataGrid。问题是,该型Plant
具有ICollection<PlantType>
类型的成员为我需要在数据网格中作为一个字符串对应的列中显示,其中在ICollection的每个项目是在一个新行是这样的:C#DataGrid充满了多层次的列表
"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 |
-----------------------------------------
目前最大的问题是,它只是在名称和页面填写(因为这些都不是HashSets,因此明确)。这是我为填充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);
}
我试过的事情,但已经江郎才尽了与谷歌的搜索字词。有人能告诉我如何正确地将Type
绑定到列这种方式吗?
你想要的观点的例子有点不清楚。你是说在每个'Plant'实例中应该有一行,然后在各自的'ICollection'中为每个'PlantType'实例设置一行? –
blins
是的,有点不清楚,对不起。我的意思是,类型应该与最初的工厂列在同一行,但用逗号和换行符分开。在“测试”的例子中,“此类型”和“类型”与“不支持”(全部是名称:pla2的一部分)在同一行,但是以列出的形式。 为了更清楚:Plantname |页面|植物类型(列出,因为一次可以有多个) – Vitriol
我将创建一个'PlantViewModel'类,它具有类型为'Type'的属性以及相同的属性'Name'和'Page'。然后我会将'Plant'映射到'PlantViewModel',最后绑定到PlantViewModels。 – blins