Xamarin Forms CollectionView ScrollTo when called externally

BananaSupreme 1 Reputation point
2021-03-05T06:49:56.457+00:00

I have this control that is mainly a collectionview and occasionally I have to use changes elsewhere to scroll the collectionview, so I exposed a ScrollTo method which I am triggering when an event in another control is called.

I only tested on android.

I followed breakpoints and ScrollTo is being called but no scrolling happens, (scrolling actually doesnt work also when the page is loaded, or when on appearing calls it in the page that implements the control, for the first one I saw the response, and since its a contentview and not contentpage I dont have OnAppearing to use) I have an OnScrolled Event Attached that isn't called as well.

I am also sure it is meant to scroll as the index I am calling is not the one I have;

Exposed ScrollTo

public void ScrollToOffset(int Offset, bool animate = true)
        {
            int index = currentIndex + Offset;
            collectionView.ScrollTo(index: index, animate: animate);
        }

Calling Code

public void OnEvent(object sender, EventArgs e)
        {
            Control.ScrollToOffset(1);
        }

I verified it is calling on UI thread by using Device.BeginInvokeOnMainThread() and trying to Focus the objects doesn't seem to help.
The call I placed in the OnAppearing does seem to work when is called by HotReload but the one called by the event still doesn't work.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,288 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,751 Reputation points
    2021-03-05T08:52:03.383+00:00

    Hello,

    Welcome to Microsoft Q&A!

    You can call the method in SizeChanged event .

       bool isFirstLoading = true;  
               public YourPage()  
               {  
                   InitializeComponent();  
                   BindingContext = new MonkeysViewModel();  
         
                   this.SizeChanged += (sender,e)=> {  
                       if (isFirstLoading)  
                       {  
                           collectionView.ScrollTo(index: 10);  
                           isFirstLoading = false;  
                       }  
                   };  
               }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.