Search code examples
xamarin.iosxamarinuicollectionviewmvvmcross

UICollectionview SelectItem programmatically not changing background


I have a UICollectionView with images. The user can select (multiselect) the images. When the user taps a single image, everything works fine. The SelectedBackgroundView is visible and on tap again, the normal image is visible.

But my problem is, I have a option for the user "Select all". In that i want to select all items programmatically. With following code:

for (int i = 0; i < CollectionView.NumberOfItemsInSection(0); i++)
{
    var ip = NSIndexPath.FromItemSection(i, 0);
    CollectionView.SelectItem(ip, false, UICollectionViewScrollPosition.None);
}

The following method returns the correct number for the selected items:

var number = CollectionView.GetIndexPathsForSelectedItems().Length;

But the UI is not changing to the SelectedBackgroundView.

Can anyone help me? Thanks.


Solution

  • Calling SelectItem does not cause the display to be updated; it just changes the Selected property of the UICollectionViewCell therefore updating the selected index set in the collection view.

    What I do is override the Selected property of my UICollectionViewCell implementation and adjust the UI at that point:

    public class MyCell : UICollectionViewCell
    {
        // ...
        public override bool Selected
        {
            get { return base.Selected; }
            set
            {
                base.Selected = value;
                // change the state of the selected background
                imageBackground.Image = LoadAnImage(value ? "BackgroundOn" : "BackgroundOff");
            }
        }
    }
    

    This way ensures that the UI is updated at all possible points when the selected state of the cell changes, either by user interaction or programmatically calling SelectItem or DeselectItem on the collection view.

    I do not personally use the SelectedBackgroundView property on a cell (I do my own layering, most of the time), but you may have to manually bring that view to the front yourself in a similar Selected property override.