1

aDataGrid可以绑定到Collection<List>类型吗?

DataGrid关于将 a 绑定到 a有几个问题Collection<Collection>,它也对我有用。但是,我正在专门寻找DataGrid<-- Binding --> Collection<List>


当我尝试时,List它只是显示为DataGrid类似的对象:

名称
- System.Collections.Generic.List'1[System.Int32]

Bob
23
43000
+ System.Collections.Generic.List'1[System.Int32]


在这种情况下a 与 aList有何不同?Collection

AList没有条目标识符,因此 List 中的条目不能自动分组到 a 中的列中DataGrid

例子:

Collection<List>
entry1 包含List:“Bob”, 23, 43000,
entry2 包含List:“Alice”, 42, 71000。

我可以使用 aDataTemplateList获得以下显示吗?
姓名 | 年龄 | 工资
鲍勃 ​​| 23 | 43000
爱丽丝 | 42 | 71000

请注意,字符串 Name、Age 和 Salary 不是Lists.


我的计划

  1. 将标题行绑定到 aList<String>以获取DataGrid's标题中的列名。
  2. 将剩余的行绑定到Collection<List>以获取填充到DataGrid.

具体来说,我想知道是否可以将这 3 个字符串(姓名、年龄、薪水)放入 a 中List<String>并仅将标题行绑定到它。其余行DataGrid可以绑定到 Collection。

这甚至可能吗?


理想情况下,我想使用Infragistics' XamDataGrid,但任何解决方案DataGrid都是一个很好的起点。


编辑

为什么我不用Collection<Employee>?我想只显示.DataGrid

我有大约 5 个屏幕,显示来自 2 种类型的列EmployeeEmployeeDetails. 这两种类型都有大约 100 个不同的属性,我只对在每个屏幕上将大约 20 个属性显示为列感兴趣。因此,我List为每个仅包含这 20 个属性的Employee/对象创建了一个。EmployeeDetails

该子集是在运行时通过读取一些配置文件来定义的。因此,我无法静态定义我需要展示的内容。

4

2 回答 2

2

You could use a binding converter to extract a member of your list:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (value is List<string> && parameter is int)
    {
        return ((List<string>)value)[(int)parameter];
    }

    return null;
}

... but honestly I don't understand what you're trying to achieve. Your list of strings represents the properties of an object, why don't just use a Collection<Employee> where Employee is

public class Employee : INotifyPropertyChanged
{
    public string Bob
    {
        ...
    }

    public int Age
    {
        ...
    }

    public double Salary
    {
        ...
    }
}

Strongly typed, much more readable, much more maintainable.


EDIT:

After reading your edit: definitely don't use a List<string>. Simply do not ask your XamDataGrid to automatically generate a column for each field. You've also some examples about how to hide columns.


EDIT:

It's way much more MVVM friendly to expose a Collection<Employee> property + write some code behind, than to expose Collection<List<string>>.

Remember the limitations of the XamDataGrid control are purely related to the view part of the MVVM pattern. Don't change the ViewModel logic because of that.

Also here's a related question that could help: XamDataGrid column visibilty is not working using MVVM

于 2012-08-16T16:48:10.067 回答
1

这听起来不对。您在集合中显示的项目只是具有属性的对象。为什么不只是拥有具有这些属性的对象集合呢?

为了迭代第二个列表,您需要绑定到该列表的绑定行内的另一个 ItemsControl 作为其数据源。否则,您将始终只收到 System.Collections.Generic.List'1[System.Int32] 绑定值,因为这是正在迭代的内容的当前级别。

如果你想让它保持通用,你甚至可以绑定到一个集合,允许对象定义它的属性,并且在 Datagrid 中,只绑定到它认为应该可见的属性(无论对象是否支持)。

于 2012-08-16T16:35:46.007 回答