2

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.

Shaddix
  • 5,901
  • 8
  • 45
  • 86

1 Answers1

3

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.

Community
  • 1
  • 1
Stuart
  • 66,722
  • 7
  • 114
  • 165
  • Thanks Stuart, I'll mark this as an answer, since it's completely correct. For me, I was just dumb to use `NSIndexPath.FromIndex` instead of `NSIndexPath.FromItemSection`. Now using the latter and everything's great. – Shaddix Jun 30 '14 at 03:49