简体   繁体   中英

Create a sub-row/child row in datagrid from a list of objects in my parent object C# WPF

So let's say for this example I have an object of type car right. The car class is as follows:

class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public List<Wheel> Wheels { get; set; }
}

and the Wheel class is as follows:

class Wheel
{
    public int ID { get; set; }
    public string Size { get; set; }
    public string Shape { get; set; }
    public string Brand{ get; set; }
}

so basically what I want is for the List<Wheel> wheels to display in a sub row/child row

See screenshot below:

我想要的是

I am working in C# WPF

Here is how you can display your data in nested grid way

    <DataGrid ItemsSource="{Binding Path=Cars}" AutoGenerateColumns="false"
              RowDetailsVisibilityMode="Visible"
              CanUserAddRows="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Make" Binding="{Binding Make}"/>
            <DataGridTextColumn Header="Model" Binding="{Binding Model}"/>
        </DataGrid.Columns>
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <DataGrid ItemsSource="{Binding Path=Wheels}" AutoGenerateColumns="false" CanUserAddRows="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"/>
                        <DataGridTextColumn Header="Size" Binding="{Binding Path=Size}" IsReadOnly="True"/>
                        <DataGridTextColumn Header="Shape" Binding="{Binding Path=Shape}" IsReadOnly="True"/>
                        <DataGridTextColumn Header="Brand" Binding="{Binding Path=Brand}" IsReadOnly="True"/>
                    </DataGrid.Columns>
                </DataGrid>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM