Scroll to top of Xamarin Forms ListView with title

I'm having trouble scrolling to the top of ListView in Xamarin Forms. I can go to the first element by calling ScrollTo and passing the first element. The problem is that when the list has a title element, I cannot find a way to scroll to the title. Is it possible? The only work I can think of is not to use a title and just have another element at the top of the ItemSource that acts like a title, but I would prefer to use a title if possible. Thank you

+7
xamarin xamarin.forms
source share
2 answers

So, I solved it now. My solution was to subclass ListView and add a public ScrollToTop method that calls the internal call to ScrollToTopRequestedEvent when called. Then I subclassed the ListViewRenderer on each platform and registered for the event.

In the Android renderer, I call Control.SmoothScrollToPositionFromTop (0, 0) to scroll up.

In iOS rendering, I call Control.ScrollRectToVisible (new CoreGraphics.CGRect (0, 0, 1, 1), true).

+11
source share

Wah all credits @Gareth Wynn, man who was cool thanks. In any case, here is the code for everyone to use, change class names and namespace, iOS is not included, do the same as for Android, just using the Gareth Wynn hint in the parallel answer:

SHARED NiftyListView.cs :

  using System; using Xamarin.Forms; namespace AppoMobi { public class NiftyListView : CListView { public event EventHandler EventScrollToTop; //------------------------------------------------------------------- public void ScrollToTop(bool animate=true) //------------------------------------------------------------------- { //bool animate is not used at this stage, it always animated. EventScrollToTop?.Invoke(this, EventArgs.Empty); } } } 

ANDROID NiftyListView.Android.cs :

 using System; using AppoMobi; using AppoMobi.Droid.Renderers; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using ListView = Xamarin.Forms.ListView; [assembly: ExportRenderer(typeof(NiftyListView), typeof(NiftyListViewRenderer))] namespace AppoMobi.Droid.Renderers { //------------------------------------------------------------------- class NiftyListViewRenderer : ListViewRenderer //------------------------------------------------------------------- { protected override void OnElementChanged(ElementChangedEventArgs<ListView> e) { base.OnElementChanged(e); var view = (NiftyListView)Element; if (view == null) return; view.EventScrollToTop += OnScrollToTop; } //------------------------------------------------------------------------------------------- public async void OnScrollToTop(object sender, EventArgs eventArgs) //------------------------------------------------------------------------------------------- { Control.SmoothScrollToPositionFromTop(0, 0); } } } 
+2
source share

All Articles