我正在尝试将 Bindings 与 ListBoxes 一起使用来显示在 JSON 文件中提供的菜单。问题是如果我使用下面的代码,下面的“MenuEntryTemplate”的内容不会显示,如果我将列表框直接放在 CantineTemplate 中并使用 {Binding Meal.Lunch} 和 {Binding Meal.Dinner} 它们确实有效,所以我想知道为什么添加这个额外的级别会破坏代码。
我有以下一段 JSON(我无法更改其格式):
"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"
}
]
}
}
]
我使用 Json.Net 对其进行反序列化,这似乎将我的对象正确反序列化为以下数据结构:
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; }
}
我的 XAML 如下所示:
<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>