I am trying to use Bindings with ListBoxes to display a menu which is delivered in a JSON file. The problem is that the content of the “MenuEntryTemplate” below does not get displayed if I use the code below, if I place the listboxes in the CantineTemplate directly and use {Binding Meal.Lunch} and {Binding Meal.Dinner} they do work, so I wonder why adding this extra level breaks the code.
I have the following piece of JSON (for which I cannot change the format):
"cantines": [
{
"name": "Canteen A",
"meal": {
"lunch": [
{
"type": "soup",
"name": "Vegetable soup"
},
{
"type": "main",
"name": "Burger with fries"
},
],
"dinner": [
{
"type": "main",
"name": "Chicken breast with rice"
}
]
}
}
]
I deserialize this using Json.Net, which seems to properly deserialize my object into the following data structure:
public class MenuModel : ViewModelBase
{
public List<Cantines> Cantines { get; set; }
}
public class Cantines
{
public string Name { get; set; }
public Meals Meal { get; set; }
}
public class Meals
{
public List<Lunches> Lunch { get; set; }
public List<Dinners> Dinner { get; set; }
}
public class Lunches
{
public string Type { get; set; }
public string Name { get; set; }
}
public class Dinners
{
public string Type { get; set; }
public string Name { get; set; }
}
My XAML looks as follows:
<DataTemplate x:Key="MealEntryTemplate">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Type}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="MealTemplate">
<StackPanel>
<!-- These 2 listboxes do not show up, when I leave this MealTemplate out and
use {Binding Meal.Lunch} in the "CantineTemplate" it does work. -->
<ListBox
ItemsSource="{Binding Lunch}"
ItemTemplate="{StaticResource MealEntryTemplate}"
/>
<ListBox
ItemsSource="{Binding Dinner}"
ItemTemplate="{StaticResource MealEntryTemplate}"
/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="CantineTemplate">
<ListBox
ItemsSource="{Binding Meal}"
ItemTemplate="{StaticResource MealTemplate}"
/>
</DataTemplate>
<DataTemplate x:Key="MenuTemplate">
<ListBox
ItemsSource="{Binding Cantines}"
ItemTemplate="{StaticResource CantineTemplate}"
/>
</DataTemplate>
The property
Mealis a singleMealsobject. A listbox expects a collection of objects, that’s why it isn’t working. You could declare theMealproperty as aList<Meals>to make it work, but I don’t see the point of using a listbox if there’s only one element.