Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deserialize JSON arrays and bind resulting objects to WPF DataGrids?

Given a JSON file with two arrays (let's say one named "people" and one named "places"):

{
    "people": [{
        "name": "Adam",
        "age": 24
    }, {
        "name": "Bill",
        "age": 26
    }, {
        "name": "Charlie",
        "age": 28
    }],
    "places": [{
        "city": "San Francisco",
        "population": 850000
    }, {
        "city": "New York",
        "population": 8400000
    }, {
        "city": "Chicago",
        "population": 2700000
    }]
}

I am loading that from disk and deserializing the JSON using JSON.NET:

using (var sr = new StreamReader(path))
{
    var json = sr.ReadToEnd();
    _content = JsonConvert.DeserializeObject(json);
}

Where _content is an instance variable declared dynamic. After parsing, this ends up containing a value of type System.Collections.Generic.Dictionary<string, object>. Now, I want to display this data in two DataGrids:

<DockPanel>
    <DataGrid x:Name="leftPane" DockPanel.Dock="Left">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name"/>
            <DataGridTextColumn Header="Age"/>
        </DataGrid.Columns>
    </DataGrid>
    <DataGrid x:Name="rightPane" DockPanel.Dock="Right">
        <DataGrid.Columns>
            <DataGridTextColumn Header="City"/>
            <DataGridTextColumn Header="Population"/>
        </DataGrid.Columns>
    </DataGrid>
</DockPanel>

I know I need to add "Binding" attributes to the DataGridTextColumns, and perhaps a "DataContext" to the DataGrids, but I don't know what to put in there. Most of the binding tutorials out there show how to bind to StaticResources or classes with properties, but not to the JObject hierarchies that JSON.Net deserializes to.

like image 833
Ryan Avatar asked Sep 26 '22 07:09

Ryan


1 Answers

Set DataContext

public MainWindow()
    {
        InitializeComponent();

        // you will get entries using your code, I hard-coded anonymous objects
        Dictionary<string, object> entries = new Dictionary<string, object>();
        entries.Add("People", new [] { new { Name = "name1", Age = 24 } });
        entries.Add("Places", new[] { new { City = "agra", Country = "India" } });

        this.DataContext = entries;
    }

XAML

    <DataGrid x:Name="leftPane" ItemsSource="{Binding .[People]}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
        </DataGrid.Columns>
    </DataGrid>
like image 148
AnjumSKhan Avatar answered Sep 28 '22 05:09

AnjumSKhan