开发者

Different sized vertical cell widths in a WPF Datagrid control

开发者 https://www.devze.com 2023-01-21 00:55 出处:网络
I have a collection of Person objects that I want to display in a WPF Datagrid. The class definition for Person is:

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

class Person {
  str开发者_开发知识库ing 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?


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>();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消