【发布时间】:2012-09-15 06:22:04
【问题描述】:
我有一个 List 的对象,其中包含另一个 List。我想将两个Lists 绑定到不同的控件(一个嵌套在另一个控件中 - 一个ListView 作为GridViewItem)。但我无法让xaml 工作。
非常接近这个问题的是Binding List of Lists in XAML?。
MSDN 文档中有一篇关于此的文章:
How to bind to hierarchical data and create a master/details view - 可能是解决方案,但我发现很难将其应用于我的代码。
其他文章涉及这个主题,但不是很好,而且作为一个新用户,我不允许在一个问题中包含两个以上的超链接。
我的代码看起来与此类似(为了清楚起见,更改为城市/餐厅场景):
型号:
public class City
{
string Name { get; set; }
List<Restaurant> RestaurantList { get; set; }
//.. also a constructor with parameters for the properties and an overriding toString method that returns Name
}
public class Restaurant
{
string Name { get; set; }
List<Uri> UriList { get; set; }
//.. also a constructor with parameters for the properties and an overriding toString method that returns Name
}
代码隐藏(LoadState 方法):
//.. getting a List of cities (with restaurants), that is being created in some model class
this.DefaultViewModel["Items"] = Cities;
有些人改为设置DataContext。我从 MSDN 教程中得到了这个,它到目前为止工作。但我不确定哪个“更好”。
现在 XAML 好了:
我想要一个GridView,城市为GridViewItems。在一个GridViewItem 中有一个Grid,在顶行显示City 的Name,在下面显示ListView。 ListView 包含 Restaurants(仅是 City!)。 ListViewItems 只是 TextBlocks 显示 Restaurant 的 Name。
我只希望Restaurants 可以点击。
像这样:
<!-- the following line is at the very top and the reason why it should work without setting DataContext explicitly -->
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
<!-- ... -->
<GridView Grid.Row="1" ItemsSource="{Binding Items}" SelectionMode="None">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="500" Width="200" Margin="50" Background="Gray">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="5*"/>
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Text="{Binding Name}"/>
<ListView
Grid.Row="1"
ItemsSource="{Binding RestaurantList}" IsItemClickEnabled="True">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Tapped="Restaurant_Click"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
这样只会显示灰色框。将TextBlock 的绑定更改为Text="{Binding}" 时,至少会显示城市的Names。我不明白也不想要,因为我猜toString 方法的覆盖并不意味着以这种方式使用。 Restaurants 中的 Names 在这两种情况下都不会出现。
此外,这个视图中的滚动不知何故中断了,但我想这是一个不同的故事。
那么:XAML 中的数据绑定有什么问题?
【问题讨论】:
-
欢迎!数据绑定需要公共属性:例如
public string Name { get; set; }和public List<Restaurant> RestaurantList { get; set; }。是样本中的“错字”还是问题的根源? -
天哪!实际上就是这样!非常感谢!当你把它作为一个答案时,我会相应地标记它。
标签: xaml c# xaml data-binding windows-8 windows-runtime