Search code examples
windows-phone-7windows-phone

Update MultiselectList selected items


I'm using MultiselectList from Controls.Toolkit. I use it as a favourite selector. I have a list with items, I select the favourites and the next time I open the selection bar I would like to see my favourites already selected. When IsSelectionEnabledChanged event occurs, if IsSelectionEnabled is true (the selection bar is opened) I try to add my favourites to the list's SelectedItems. Here is a code snippet:

private void multiSelectList_IsSelectionEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (multiSelectList.IsSelectionEnabled)
        {
            foreach (var favourite in FavouritesList)
            {
                multiSelectList.SelectedItems.Add(multiSelectList.Items.Where(i => ((MyModel)i).id == favourite.id).FirstOrDefault());
            }
        }
   }

I have tested this solution and I found out that the layout does not update the entire list that's why I'm not seeing the items as selected (but they are). Not even the actual visible items in the list. After scrolling for a bit and scrolling back, the selection appears! I've tried to use multiSelectList.UpdateLayout() method programatically but it did not solve it.

I wonder if it is a visualization problem or a CheckBox binding problem (the selection uses CheckBox on the side).


Solution

  • The SelectedItems is just a List<object>, it doesn’t raise any events when you update it. To update your items manually, you could do something like following instead (untested code):

    private void multiSelectList_IsSelectionEnabledChanged( object sender, DependencyPropertyChangedEventArgs e )
    {
        if( !multiSelectList.IsSelectionEnabled )
            return;
    
        var dictSelected = FavouritesList.ToDictionary( f => f.id, f => true );
    
        for( int i = 0; i < multiSelectList.Items.Count; i++ )
        {
            MyModel m = (MyModel)multiSelectList.Items[ i ];
            if( !dictSelected.ContainsKey( m.id ) )
                continue; // Not selected
    
            MultiselectItem item = (MultiselectItem)multiSelectList.ItemContainerGenerator.ContainerFromIndex( i );
            if( null != item )
                item.IsSelected = true; // This should add the item into the SelectedItems collection.
            else
                multiSelectList.SelectedItems.Add( m ); // The item is virtualized and has no visual representation yet.
        }
    }