Articles in this section
Category / Section

How to maintain the scroll position of ListView after clearing the filter at runtime?

1 min read

The scroll position of the ListView can be maintained when items are filtered and cleared using the OnFilterTextChanged event of search bar. For example, the initial scroll position should be maintained when applying and clearing the filter of the items at runtime.

C#

public class Behaviours: Behavior<SfListView>
{
   private SfListView listView;
   private SearchBar searchBar = null;
   ExtendedScrollView scrollview;
   double position;
   protected override void OnAttachedTo(BindableObject bindable)
   {
      listView = bindable as SfListView;
      searchBar = (bindable as SfListView).FindByName<SearchBar>("filterText");
      searchBar.TextChanged += SearchBar_TextChanged;
      scrollview = listView.GetScrollView();
      base.OnAttachedTo(bindable);
   }
 
   protected override void OnDetachingFrom(BindableObject bindable)
   {
      listView = null;
      searchBar = null;
      searchBar.TextChanged -= SearchBar_TextChanged;
      base.OnDetachingFrom(bindable);
   }
   
   private bool FilterContacts(object obj)
   {
      if (searchBar == null || searchBar.Text == null)
         return true;
 
      var contacts = obj as Contacts;
      if (contacts.ContactName.ToLower().Contains(searchBar.Text.ToLower())
                || contacts.ContactName.ToLower().Contains(searchBar.Text.ToLower()))
         return true;
      else
         return false;
   }
 
   private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
   {
      if (searchBar.Text != "")
         position = scrollview.ScrollY;
 
      searchBar = (sender as SearchBar);
      if (listView.DataSource != null)
      {
         this.listView.DataSource.Filter = FilterContacts;
         this.listView.DataSource.RefreshFilter();
      }
      if (searchBar.Text == "")
         listView.ScrollTo(position);
      else if (searchBar.Text == "")
         listView.ScrollTo(position);
   }
}

 

Click here to download the sample.

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied