How do I implement pull-to-refresh in a ListView?

Platform: .NET MAUI| Category: Controls

To enable pull-to-refresh, set the ‘IsPullToRefreshEnabled’ property to ‘true’ and specify a ‘RefreshCommand’. Users can then pull down the list to initiate the refresh action.  

XAML

<ContentPage.BindingContext>
     <local:BookViewModel />
 </ContentPage.BindingContext>
 <StackLayout>
     <ListView ItemsSource="{Binding Books}"
       IsPullToRefreshEnabled="true"
       RefreshCommand="{Binding RefreshCommand}"
       IsRefreshing="{Binding IsRefreshing}">
         <ListView.ItemTemplate>
             <DataTemplate>
                 <TextCell Text="{Binding Title}" />
             </DataTemplate>
         </ListView.ItemTemplate>
     </ListView>
 </StackLayout>

C#-MVVM

namespace PullToRefreshDemo.ViewModels;
public class Book
 {
     public string Title{ get; set; }
 }
public class BookViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Book> Books { get; set; }
    public ICommand RefreshCommand { get; private set; }
    private bool isRefreshing;
    public bool IsRefreshing
    {
        get { return isRefreshing; }
        set { isRefreshing = value; OnPropertyChanged("IsRefreshing"); }
    }
    public BookViewModel()
    {
        Books = new ObservableCollection<Book>
        {
            new Book { Title = "Book 1" },
            new Book { Title = "Book 2" },
            new Book { Title = "Book 3" }
        };
        RefreshCommand = new Command(async () => await RefreshData());
    }
    private async Task RefreshData()
    {
        await Task.Delay(2000);    // Refresh Delay
        // Add new data or update existing data
        Books.Clear();
        Books.Add(new Book { Title = "Book 4" });
        Books.Add(new Book { Title = "Book 5" });
        IsRefreshing = false;     // Reset the IsRefreshing property to indicate that the refresh is complete
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName))}
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.