在WPF中显示嵌套数据

时间:2013-07-08 11:01:18

标签: c# .net wpf

如何在DataGrid中显示Person对象的集合,以便也可以查看有关Person,Address,Dependents和Awards的信息。

public class Person
{
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public Address Address { get; set; }
        public IList<Dependent> Dependents { get; set; }
        public IList<Award> Awards { get; set; }
}

public class Address
{
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
}

public class Dependent
{
        public string DependentName { get; set; }
        public int DependentAge { get; set; }
}

public class Award
{
        public string AwardName { get; set; }
        public DateTime AwardDate { get; set; }
}

1 个答案:

答案 0 :(得分:1)

一种选择是使用DataGridTemplateColumn

<DataGrid ItemsSource="{Binding MyItems}">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <!-- template for Address, Dependent or Awards types -->
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

第二个选项是使用row details

第三个选项是使用一些控件来显示所选行的详细信息:

<DataGrid x:Name="myGrid" ItemsSource="{Binding MyItems}">
    <!-- The rest of grid here -->
</DataGrid>

<ContentControl Content="{Binding SelectedItem, ElementName=myGrid}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <!-- The template for person's details -->
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>