I have a ListView in which two pages (Pn and Vt) are switched using buttons. And these pages need to be filled out from such JSON.

{ "Pn" : [ { "Number" : "1", "Time" : "08:30 - 09:15", "Yrok" : [ { "Kb" : "Щелковское шоссе, № 122", "Name" : "Музыка" } ] }, { "Number" : "2", "Time" : "09:25 - 10:10", "Yrok" : [ { "Kb" : "Щелковское шоссе, № 107", "Name" : "История" } ] } ], "Vt" : [ { "Number" : "1", "Time" : "08:30 - 09:15", "Yrok" : [ { "Kb" : "Щелковское шоссе, № 115", "Name" : "Математика" } ] }, { "Number" : "2", "Time" : "09:25 - 10:10", "Yrok" : [ { "Kb" : "Щелковское шоссе, № с/з", "Name" : "Физ-ра" } ] } ] } 

That is, these variables will be displayed in a single ListView element.

 "Number" : "1", "Time" : "08:30 - 09:15", "Yrok" : [ { "Kb" : "Щелковское шоссе, № 122", "Name" : "Музыка" } ] 

How can this be easier to do? It only occurs to me to create a loop in which I will write each variable, and then create this element of the type: listView1.Items.Add(itm)

1 answer 1

As an option, you can do this: Make two classes that write our element to json

 public class Item { public string Number { get; set; } public string Time { get; set; } public List<Yrok> Yrok { get; set; } } public class Yrok { public string Kb { get; set; } public string Name { get; set; } } 

Next, prepare the markup for binding:

 <ListView x:Name="JsonView"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Width="30" Text="{Binding Number}"> </TextBlock> <TextBlock Width="100" Text="{Binding Time}"></TextBlock> <ListView Width="300" ItemsSource="{Binding Yrok}" SelectionMode="None"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Width="200" Text="{Binding Kb}"></TextBlock> <TextBlock Width="100" Text="{Binding Name}"></TextBlock> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> 

It now remains to deserialize the data and set its ListView.ItemsSource property.

 //в data должна быть json строка, той структуры, что вы привели выше sting data=""; var json = JObject.Parse(data); List<Item> items = new List<Item>(); foreach (var key in json) { var itm = JsonConvert.DeserializeObject<List<Item>>(key.Value.ToString()); items.AddRange(itm); } JsonView.ItemsSource = items; 

And that's what comes out: enter image description here

  • And if I have several elements in Yrok? Are they really all out or only the first? - Denisok
  • @Denisok <TextBlock Width="200" Text="{Binding Yrok[0].Kb}"></TextBlock> indicates that the first one in the list is displayed. If you need everything, then either embed another ComboBox , or next to another sculpt ListBox , which will display all the Yrok at the selected item. - Bulson
  • @Denisok Fixed the markup so that everything would be displayed. - 123_123