我想动态创建Grid
以显示任何电子商务网站的产品信息。
我从JSON获取产品信息,然后想要将每个产品详细信息显示到视图中的图块。
答案 0 :(得分:1)
我的建议是使用内置ItemsControl
的{{1}},而不是使用大量代码隐藏代码。
WrapPanel
<ItemsControl ItemsSource="{Binding Products}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- Your item template -->
<Grid Height="120" Width="70">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="3*" />
<RowDefinition Height="2*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" FontWeight="Bold" Text="{Binding ProductName}" />
<Image Grid.Row="1" Source="{Binding Thumbnail}" />
<TextBlock Grid.Row="2" Text="{Binding Description}" />
</Grid>
<!-- Your item template -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
将是DataContext中的项集合(ViewModel,如果您正在使用MVVM),您只需绑定到项模板中这些项的属性(如{{我的例子中有1}},Products
或ProductName
。
优点:
缺点:
如果你想要所有奇特的功能,比如标题,选择等,你将不得不使用像DataGrid这样的东西,但是你会失去平铺的布局。