Search code examples
c#visual-studio-2012windows-phone-8custom-controlsitemscontrol

Adding custom items to stackpanel


I'm working on a project (for Windows Phone 8 with Visual Studio 2012 with C#) where I want to display some items that each have:

  1. a picture
  2. a title
  3. a description
  4. to be able to be clicked (so that I can navigate to a certain Page)

So I thought I could do that with a stackpanel. But I'm not sure how I can add items that have the above properties and to be able to add those items from XAML. I tired adding items through a ItemsControl in stackpanel but I'm not sure how I can add more complex items like the one I want.


Solution

  • The best approach is to use a ListBox or LongListSelector rather than a StackPanel. You can then:

    • Data bind the list to the control itself, which will handle adding/deleting items from the control automatically
    • Define the view for each control using ListBox's ItemTemplate property

    First of all, in your code-behind/ViewModel/what-have-you, you'll want to create an ObservableCollection of objects to display. ObservableCollection will let the control know to update in the case an item is added, removed, etc.

    public ObservableCollection<T> foo = new ObservableCollection<T>();
    

    In XAML, you'll then want to databind this ObservableCollection to the ListBox you've created:

    <ListBox x:Name="ListBox" ItemsSource="{Binding foo}" />
    

    Finally, you can define the ItemTemplate of the ListBox like so:

    <ListBox x:Name="ListBox" ItemsSource="{Binding foo}" >
       <ListBox.ItemTemplate>
          <DataTemplate>
             <StackPanel Orientation="Horizontal" Margin="2">
                <TextBlock Text="{Binding Title}" />
                <TextBlock Text="{Binding Description}" />
                <Image Source="{Binding Image}" />
             </StackPanel>
          </DataTemplate>
       </ListBox.ItemTemplate>
    </ListBox>
    

    I'd highly recommend reading this guide, especially "Binding a control to a collection of objects" and the section after on DataTemplates. :)