C#/WP7绑定到JsonNet中包含JSON数组的对象



我正在尝试使用带有ListBoxes的Bindings来显示JSON文件中提供的菜单。问题是,如果我使用下面的代码,下面的"MenuEntryTemplate"的内容不会显示,如果我直接将列表框放在CantineTemplate中并使用{Binding Meal.Lunch}和{Binding Fool.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>
<ListBox
ItemsSource="{Binding Meal}"
ItemTemplate="{StaticResource MealTemplate}"
/>

属性Meal是单个Meals对象。列表框需要一个对象集合,这就是它不起作用的原因。您可以将Meal属性声明为List<Meals>以使其工作,但如果只有一个元素,我认为使用列表框没有意义。

最新更新