Xamarin Forms - Binding Listview for lazy loading

孤街醉人 提交于 2019-12-05 22:29:11

First, create a view model class, called MyViewModel.cs:

public class MyViewModel : INotifyPropertyChanged
{
    // property changed event handler
    public event PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<Mainlist> _list;

    public ObservableCollection<Mainlist> List
    {
        get { return _list; }
        set
        {
            _list = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(List)));
        }
    }

    public MyViewModel()
    {
        _list = new ObservableCollection<Mainlist>();
    }

    public async void StartScraping()
    {
        // assuming you are 'awaiting' the results of your scraping method...
        foreach (...)
        {
            await ... scrape a web page ...

            var newItem = new Mainlist()
            {
                Title = title.ToString().Trim(),
                Value = value.ToString().Trim()
            };

            // if you instead have multiple items to add at this point,
            // then just create a new List<Mainlist>, add your items to it,
            // then add that list to the ObservableCollection List.

            Device.BeginInvokeOnMainThread(() => 
            {
                List.Add(newItem);
            });
        }

    }
}

Now in your page's xaml.cs code behind file, set the view model as your BindingContext:

public class MyPage : ContentPage // (assuming the page is called "MyPage" and is of type ContentPage)
{
    MyViewModel _viewModel;

    public MyPage()
    {
        InitializeComponent();
        _viewModel = new MyViewModel();
        BindingContext = _viewModel;
        // bind the view model's List property to the list view's ItemsSource:
        mainList.setBinding(ListView.ItemsSourceProperty, "List");
    }
}

And note that in your view model, you'll need to use an ObservableCollection<T> instead of a List<T>, as ObservableCollection<T> will allow the ListView to be updated automatically whenever you add or remove items from it.

Also, to ease a bit of confusion, I'd recommend changing the class name from Mainlist to MainListItem.

I think you could do something like this:

mainlist.ItemsSource = new ObservableCollection<Mainlist>();

foreach (var item in yourDataFromHtmlAgilityPackScraping) {
    mainlist.ItemsSource.Add(new Mainlist()
            {
                //scraped info from each URL
                Title = item.title.ToString().Trim(),
                Value = item.value.ToString().Trim(),
            });
}

The important part here is the ObservableCollection. Which allows the Listview to be updated when a new element is added.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!