views:

1451

answers:

3

What's the best way to add children to a WrapPanel in silverlight? I'm using C# and I'm reading in a JSON Object containing images with thumbnails and related information.

The end goal is to have a grid of thumbnails (13 thumbs horizontally across 950px by 6 thumbs vertically).

A: 

The WrapPanel is derives from Panel so you can just use Children.Add(control). The WrapPanel will take care of all the layout, that is its job.

Maurice
+4  A: 

When you're faced with adding items in code, generally there's a better way.

How about making a ListBox and setting its ItemsSource to your list (or binding it to the DataContext). Make a DataTemplate to display your thumbnail + info and then (this is the important part) make a ItemsPanelTemplate using a WrapPanel.

<Grid x:Name="ImageThumbnails">
    <ListBox 
        ItemsSource="{Binding}" 
        Width="950"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <Image Source="{Binding Thumbnail}" Width="80" Height="60"/>
                    <TextBlock Text="{Binding ImageName}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
     </ListBox>
</Grid>

Then in your code, once you've got your data from your JSON call:

this.ImageThumbnails.DataContext = thumbnailListFromJSON;

Now if your list is an ObservableCollection, then any changes to the list will be automatically reflected in your UI.

(The above code should be treated as pseudo-code - obviously you're going to have to change it to reflect your data structure)

Edit: added ScrollViewer.HorizontalScrollBarVisibility="Disabled" to ListBox. This is important because it stops the scrollviewer expanding infinitely in the horizontal direction. Without this WrapPanel becomes a 1-row listbox.

geofftnz
A: 

The UniformGrid would be perfect for this situation. Unfortunately it is not part of the Silverlight framework. However there are a few port's of the WPF version available.

http://www.jeff.wilcox.name/2009/01/uniform-grid/

cosullivan