'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 1:[1]

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.

Solution 2:[2]

When scrolling an item into view, the exact position of the item after the scroll has completed can be specified with the position argument of the ScrollTo methods. This argument accepts a ScrollToPosition enumeration member.

CollectionView defines properties, which are backed by bindable properties

Control scroll position - Microsoft Docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phat Huynh
Solution 2 GPManuel