1
votes

Is there a way to populate the Silverlight toolkit's WrapPanel via binding to an ObservableCollection? All the examples I've seen so far, including the toolkit example itself, either populate the WrapPanel programmatically or by explicitly adding each item in XAML.

Thanks for your help!

EDIT: Following Geert van Horrik's advice I tried using an ItemsControl to load the WrapPanel via binding. This is the XAML:

<ScrollViewer VerticalScrollBarVisibility="Auto"
              Height="440"
              Margin="0,12,0,0">

  <ItemsControl ItemsSource="{Binding SelectionContent}">
    <ItemsControl.ItemTemplate>
      <DataTemplate>

        <Border BorderThickness="1"
                CornerRadius="4"
                BorderBrush="{Binding BorderBrush}">

          <toolkit:GestureService.GestureListener>
            <toolkit:GestureListener Tap="OnWrapPanelTapped"
                                     DoubleTap="OnWrapPanelDoubleTapped" />
          </toolkit:GestureService.GestureListener>

          <Image Source="{Binding ImageSource}"
                 MaxHeight="48"
                 MaxWidth="48"
                 Margin="16" />
        </Border>

      </DataTemplate>
    </ItemsControl.ItemTemplate>

    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <toolkit:WrapPanel />
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
  </ItemsControl>
</ScrollViewer>

SelectionContent is an ObservableCollection present in this UserControl's code behind. It consists of SelectionItem object, which implements INotifyPropertyChanged and exposes 2 public properties - ImageSource and BorderBrush.

I'm setting the DataContext for the UserControl in its constructor to SelectionContent. But this isn't working and the WrapPanel does not display anything.

1
You should check your output window. It will show binding errors. If you set the DataContext to "SelectionContent", you can't set the ItemsSource to "SelectionContent" again. If you want to set the DataContext to "SelectionContent" (I'd prefer a view model, but that's my opinion), use ItemsSource="{Binding}" (which binds to the current DataContext, which is "SelectionContent"). - Geert van Horrik
Brilliant! That was it, setting both to SelectionContent was indeed the problem, I set ` ItemsSource="{Binding}"` and it fixed the problem. - Praetorian

1 Answers

3
votes

You should use an ItemsControl. Then, you can set the WrapPanel as items panel.

<ItemsControl ItemsSource="{Binding MyItemsSource}">
  <ItemsControl.ItemsPanel>
    <WrapPanel />
  </ItemsControl.ItemsPanel>
</ItemsControl>