tags:

views:

18

answers:

1

I have a collection of Person objects that I want to display in a WPF Datagrid. The class definition for Person is:

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

I want to display a collection of Persons in a table. Because a person can have multiple favorite foods, I want all those favorite foods in a single cell stacked vertically in the "Favorite Foods" column for each person. Is there an easy way to bind my collection of Person objects to a Datagrid to accomplish this?

+2  A: 

Yes. Use a DataGridTemplateColumn for the "FavoriteFoods" column and within the template, just use an ItemsControl to display the collection. Something like this:

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>

Code-Behind:

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>();
    }
}
karmicpuppet
Wow, I just have to comment on the quality of this response. Fast, concise, and a perfect example. Thanks karmicpuppet.
Matthew