WP Toolkit : Adding a item in the SelectedItems collection of a LongListMultiSelector actually adds 2…

, , 3 Comments

A quick blog post about a bug I encountered today with the LongListMultiSelector : adding 2 items in its SelectedItem property actually adds 2 items (twice the same) in the SelectedItem collection.

This is quite boring because it also raises the SelectionChanged event twice and can mess up your business logic.

Let’s see how to fix this temporary (I hope!) issue :

The problem is that the LongListMultiSelector listen to the changes(add/remove/replace/clear) in it’s SelectedItem collection so we can’t use it directly.

The solution is to ‘fake’ an user selection using the LongListMultiSelectorItem which is the container of each item.

So instead of writing this code :
[csharp]
foreach (var item in LongListMultiSelector.ItemsSource)
{
//LongListMultiSelector.SelectedItems.Add(item);
}
[/csharp]

you have to write this code :
[csharp]
foreach (var item in LongListMultiSelector.ItemsSource)
{
var container = LongListMultiSelector.ContainerFromItem(item)
as LongListMultiSelectorItem;
if (container != null) container.IsSelected = true;
}
[/csharp]

 

3 Responses

Comments are closed.