Search code examples
c#xamarin.formsprismreactiveuixamarin-forms-4

How to scroll to an item using MVVM Prism and ReactiveCommand in ViewModel?


Xamarin Forms 4.0 recently released a CollectionView that lets us scroll to a specific item in a collectionView.

I have a collection view with 10 items in it that doesn't fill the screen. (Microsoft Sample Picture). I'm using ReactiveUI and MVVM Prism to handle all my logic within my ViewModel.

So far I'm able to handle navigating based on click using SelectedItem and SelectionChangedCommand. The next feature I wanted to handle was to scroll to the item I selected. I've searched through the forums and had no luck. The example only shows you how to do it in a code behind not through MVVM Prism / ReactiveUI. Thanks in advance!

<CollectionView x:Name="ScrollButtons"
                ItemsSource="{Binding MenuItems}"
                SelectedItem="{Binding SelectedMenuItem}"
                Grid.Row="2" 
                Grid.Column="0"
                Grid.ColumnSpan="2" 
                HeightRequest="90"
                SelectionMode="Single"
                SelectionChangedCommand="{Binding MenuItemSelectedCommand}"
                BackgroundColor="{DynamicResource BackgroundColorShell}">

Solution

  • I'll show you how to pass CollectionView to ViewModel.
    First, define 2 interfaces like

    public interface IHasCollectionViewModel{
      IHasCollectionView View {get;set;}
    }
    public interface IHasCollectionView{
      CollectionView CollectionView {get;}
    }
    

    Next, on your View implements IHasCollection

    public class YourView: ContentPage, IHasCollectionView {
       CollectionView CollectionView => ScrollButtons; // your CollectionView x:Name
       protected override void OnBindingContextChanged()
       {
                if (this.BindingContext is IHasCollectionViewModel hasCollectionViewModel)
                {
                    hasCollectionViewModel.View = this;
                }
                base.OnBindingContextChanged();
       }
    }
    

    Next, on your ViewModel implements IHasCollectionViewModel

    public class YourViewModel: IHasCollectionViewModel {
           public IHasCollectionView View { get; set; }
           // use CollectionView like
           private void ScrollToItem(int index){
                 View.CollectionView.ScrollTo(index); // don't forget check null
           }
    }
    

    Hope this helps.