amit srivastava
amit srivastava

Reputation: 743

How to dynamically create a grid in WPF?

I want to create a Grid dynamically to show product information like any e-commerce site.

I am fetching product information from JSON and then want to show each product details to tiles like view.

Upvotes: 1

Views: 1267

Answers (1)

almulo
almulo

Reputation: 4978

Instead of using loads of code-behind code, my suggestion is using an ItemsControl with a WrapPanel inside.

<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>

Products would be a collection of items in your DataContext (ViewModel, if you're using MVVM), and you just have to bind to the properties of those items in the Item Template (like ProductName, Thumbnail or Description in my example).

Pros:

  • Less code
  • 100% XAML
  • Adapts itself to the available space
  • Can be easily configured for horizontal or vertical, or left-to-right or right-to-left layouts

Cons:

  • No selection
  • No headers
  • No editable templates
  • Mmmh, it's not a Grid?

If you want all the fancy functionalities, like headers, selection, etc., you'll have to use something like a DataGrid, but then you lose the tiled layout.

Upvotes: 1

Related Questions