Search code examples
iosxamarin.iosxamarinmvvmcross

MvvmCross and UICollectionView how to bind SelectedItem from VM to View


I'm using MvvmCross with UICollectionView. Bindings work perfectly, I have all my data properly displayed, and even if I select an item in CollectionView it gets properly set in my ViewModel. For SelectedItem I use the following binding:

set.Bind(_collectionViewSource).For(x => x.SelectedItem).To(vm => vm.SelectedMachine);

The only problem I have is that I want a first CollectionViewItem to be selected initially. As the sources of MvvmCross say that's not supported currently (in the setter for SelectedItem):

// note that we only expect this to be called from the control/Table
// we don't have any multi-select or any scroll into view functionality here

So, what's the best way to perform initial pre-selection of an item? What's the place I can call _collectionView.SelectItem from?

I tried calling it when collection changes, but that doesn't seem to work.


Solution

  • If you need this functionality, you should be able to inherit from MvxCollectionViewSource and to add a property something like

        public event EventHandler SelectedItemExChanged;
    
        public object SelectedItemEx
        {
            get { return base.SelectedItem; }
            set
            {
                base.SelectedItem = value;
                var index = FindIndexPath(value); // find the NSIndexPath of value in the collection
                if (index != null)
                   _collectionView.SelectItem(index, true, UICollectionViewScrollPosition.CenteredHorizontally);
                var handler = SelectedItemExChanged;
                if (handler != null)
                    handler(this, EventArgs.Empty);    
            }
        }
    

    That can then be bound instead of SelectedItem

    What's the place I can call _collectionView.SelectItem from? I tried calling it when collection changes, but that doesn't seem to work.

    If that doesn't work, then I'm not sure - you are probably heading into animation timing problems - see questions like uicollectionview select an item immediately after reloaddata? - maybe try editing your question to post a bit more of your code - something that people can more easily hope with debugging.