如何在WPF中动态创建网格?

时间:2015-07-07 13:16:02

标签: wpf

我想动态创建Grid以显示任何电子商务网站的产品信息。

我从JSON获取产品信息,然后想要将每个产品详细信息显示到视图中的图块。

1 个答案:

答案 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}},ProductsProductName

优点:

  • 少代码
  • 100%XAML
  • 适应可用空间
  • 可以轻松配置水平或垂直,或从左到右或从右到左的布局

缺点:

  • 没有选择
  • 没有标题
  • 没有可编辑的模板
  • 嗯,它不是网格?

如果你想要所有奇特的功能,比如标题,选择等,你将不得不使用像DataGrid这样的东西,但是你会失去平铺的布局。