WPF Datagrid控件中不同大小的垂直单元格宽度

时间:2010-10-19 22:19:29

标签: c# wpf datagrid

我有一组Person对象,我希望在WPF Datagrid中显示。 Person的类定义是:

class Person {
  string Name;
  int Age;
  List<string> FavoriteFoods;
}

我想在表格中显示人物的集合。因为一个人可以有多种喜欢的食物,我想在每个人的“最喜欢的食物”栏中垂直堆叠的单个细胞中的所有那些喜欢的食物。有没有一种简单的方法将我的Person对象集合绑定到Datagrid来实现这一目标?

1 个答案:

答案 0 :(得分:2)

是。使用DataGridTemplateColumn作为“FavoriteFoods”列并在模板中,只需使用ItemsControl来显示集合。像这样:

XAML:

<DataGrid x:Name="dg" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
        <DataGridTextColumn Binding="{Binding Age}" Header="Age"/>
        <DataGridTemplateColumn Header="Foods">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding FavoriteFoods}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

代码隐藏:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<Person> persons = new List<Person>();

        Person p1 = new Person() { Name = "Person1", Age = 1 };
        p1.FavoriteFoods.Add("Food1");
        p1.FavoriteFoods.Add("Food2");
        p1.FavoriteFoods.Add("Food3");
        p1.FavoriteFoods.Add("Food4");

        Person p2 = new Person() { Name = "Person2", Age = 2 };
        p2.FavoriteFoods.Add("Food1");
        p2.FavoriteFoods.Add("Food2");

        Person p3 = new Person() { Name = "Person3", Age = 3 };
        p3.FavoriteFoods.Add("Food1");
        p3.FavoriteFoods.Add("Food2");
        p3.FavoriteFoods.Add("Food3");

        persons.Add(p1);
        persons.Add(p2);
        persons.Add(p3);

        dg.ItemsSource = persons;
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public List<string> FavoriteFoods { get; private set;}

    public Person()
    {
        FavoriteFoods = new List<string>();
    }
}