C# DataGrid 填充了多层列表

标签 c# wpf list binding datagrid

我已经坚持了好几天了,就是找不到自己的解决方案。我正在尝试用 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; }
}

请注意 PlantTypeType列(不是 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 模型中重新定义一些属性,这些属性也在数据模型中加上引入从 PlantPlantViewModel 的映射逻辑,并且可能反过来(如果您的 View 是可编辑的)但它促进了数据模型和 View 之间的松散耦合。

关于C# DataGrid 填充了多层列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40960444/

相关文章:

python - for 循环不断地重新开始

c# - 这个foreach中间有个cast,能翻译成linq吗?

c# - 创建在外部进程中运行的 WPF "control"

c# - 由于 System.Windows.Point/System.Drawing.PointF 差异,在 WPF/Silverlight 和 GDI+ 之间共享库时出现问题

c# - 反射调用列表中的类中的方法

python - 使用不带 `key` 的 `reverse=True` 参数按降序对字符串列表进行排序?

c# - 是否有针对 CLR 版本的 C# 预编译器定义

c# - 带有自定义序列化程序的 JSON.NET 到自定义对象

c# - BeginInvoke回调函数

wpf - 嵌入在 WPF 中的浏览器不处理指针事件