Multiple selection in Listpicker

I thought I would write a quick how-to about how to use the ListPicker for selection of multiple items.

First create a ListPicker in XAML with a few deafult strings like below:

<toolkit:ListPicker Name="myListPicker" Header="Countries" FullModeHeader="CHOOSE COUNTRIES"
SelectionChanged="myListPicker_SelectionChanged" SelectionMode="Multiple">
   <sys:String>Denmark</sys:String>
   <sys:String>Finland</sys:String>
   <sys:String>Norway</sys:String>
   <sys:String>Sweden</sys:String>
</toolkit:ListPicker>

Notice the attribute SelectionMode=”Multiple”, which sets that the user can select multiple items, we also added an event handler for the SelectionChanged event.
Note: To use < sys:string > you need to add xmlns:sys=”clr-namespace:System;assembly=mscorlib” at the top in the < phone:PhoneApplicationPage> tag.

Now in the construct for the page, add the following code:

myListPicker.SummaryForSelectedItemsDelegate = SummarizeItems;

This assigns the function SummarizeItems to summarize the string to be shown for the selected items. Let’s create that function now:

private string SummarizeItems(IList items)
{
   if(items != null && items.Count > 0)
   {
      string summarizedString = "";
      for(int i = 0; i < items.Count;i++)
      {
         summarizedString += (string)items[i];
 
         // If not last item, add a comma to seperate them
         if(i != items.Count - 1)
            summarizedString += ", ";
      }
 
      return summarizedString;
   }
   else
      return "Nothing selected";
}

This function gets an IList with all selected items and we just loop through them and add to a string with a comma between every selected item. Then we return the string, which will be shown when the list picker is in normal mode.

Hope you enjoyed this quick how-to!

No Comments Yet

You can be the first to comment!

Sorry, comments for this entry are closed at this time.