简体   繁体   中英

How to add nested objects to DataGrid C# WPF

I have a set of classes that look like the following:

public class Foo
{
    public long id { get; set; }
    public string name{ get; set; }
    public Bar bar { get; set; }
}

public class Bar
{
    public string id{ get; set; }
    public string name{ get; set; }
}

public class Wrapper
{
    public IEnumerable<Foo> foo{ get; set; }
}

After deserializing JSON the itemsource of the datagrid is mapped to the ienumerable

var myList = JsonConvert.DeserializeObject<Wrapper>(result);

myDataGrid.ItemsSource = myList;

However the problem I am having is that in the grid there are only 3 columns displayed which are the id of Foo, the name of Foo and the bar class. Rather than display the bar class I want to show the id of bar and the name of bar for a total of 4 columns but cannot figure out how to do this.

My xaml code looks like the following:

<DataGrid CanUserSortColumns="False" ItemsSource="{Binding}" x:Name="myDataGrid"/>

To bind the nested object, you should define the DataGridTextColumn (or other column type based on your requirement). Currently the columns are displayed for having AutoGenerateColumns property set to true (default value). You can update the XAML to define the data grid columns and do the binding with nested object.

<DataGrid CanUserSortColumns="False" ItemsSource="{Binding}" x:Name="myDataGrid" AutoGenerateColumns="False">
   <DataGrid.Columns>
       <DataGridTextColumn Binding="{Binding id }" Header="Id" />
        <DataGridTextColumn Binding="{Binding name}" Header="Name" />
        <DataGridTextColumn Binding="{Binding bar.id}" Header="BarId" />
        <DataGridTextColumn Binding="{Binding bar.name}" Header="BarName" />
   </DataGrid.Columns>
</DataGrid>

Without touching XAML , in code behind you can use LINQ , like:

            var myList = new Wrapper(); 
            var itemSource = myList.foo.Select(x => new {
                Id = x.id,
                Name = x.name,
                BarId = x.bar.id,
                BarName = x.bar.name
            }).ToList();
            myDataGrid.ItemsSource = itemSource;

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