Xamarin Forms: Infinite scrolling ListView

To get a dynamic “paged” loading for your list view, follow the steps below:

Make a new usercontrol in your forms project. Derive from ContentView instead from ListView. By deriving from listview, you simply can not Count the items binded to the ItemsSource property, which is the base of the Fetching logic.

public class InfiniteScrollListView : ContentView

Make a countable ItemsSource bindable property for your new usercontrol.

		public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(
														propertyName: "ItemsSource",
														returnType: typeof(IList),
														declaringType: typeof(View),
														defaultValue: null,
														defaultBindingMode: BindingMode.TwoWay,
														propertyChanged: null);

		public IList ItemsSource
		{
			get { return (IList)GetValue(ItemsSourceProperty); }
			set { SetValue(ItemsSourceProperty, value); }
		}

We need to get the usercontrol to display a listview for us. Make a new instance of a listview. You can specify a caching strategy for the listview, which can be useful on lists have a lot of items. Set the contenview’s content to the new listview instance.

		public InfiniteScrollListView()
		{
			_listViewInstance = new ListView(cachingStrategy: ListViewCachingStrategy.RecycleElement);
			_listViewInstance.HorizontalOptions = LayoutOptions.Fill;
			_listViewInstance.VerticalOptions = LayoutOptions.Fill;
			_listViewInstance.ItemAppearing += InfiniteScrollListView_ItemAppearing;
			_listViewInstance.SetBinding(ListView.ItemsSourceProperty, new Binding(nameof(ItemsSource), BindingMode.TwoWay, source: this));
			Content = _listViewInstance;
		}

		~InfiniteScrollListView()
		{
			if (_listViewInstance != null)
				_listViewInstance.ItemAppearing -= InfiniteScrollListView_ItemAppearing;
		}

The ItemAppearing event is the most important event in our Infinite scrolling listview instance. It’s called, when an item is displayed “phisically” on the screen. Let’s make an eventhandler for it. We are using a new Bindable Property for fetching data command, which will be called, when the last item of the ItemsSource has been displayed, and an another Bindable property, to turn off the fetching if the Data access layer could not provide more elements for the query. The _lastElementIndex will be the e.ItemIndex.

if (_lastItemDisplayedIndex == (ItemsSource?.Count - 1 ?? int.MinValue))
			{
				if (HasMoreItems)
				{
					if (FetchDataCommand?.CanExecute(null) == true)
					{
						FetchDataCommand?.Execute(null);
					}
				}
			}

This content has 3 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

Xamarin Forms: Auto magasságú ListView

Formsban, ha egy ListView HorizontalOptions, VerticalOptions tulajdonságait Fill-re állítjuk, és a ListView egy Grid sorában van mondjuk, amelynek a Height-je Auto, a lista le fogja foglalni a Grid által kínált összes helyet. Ez azért van, mert a ListView measure-nél még nem tudja hogy milyen listaelemek milyen listaelem formátummal fognak megjelenni benne. Így elveszítjük a lehetőséget a dinamikus megjelenítésre, mert a felületünk szét fog csúszni.

Ennek a problémakörnek megoldásaképpen készítettem egy olyan ListView-t, amely képes a listaelemek tényleges lemért magassága után újraméretezni a lista magasságát. Ez a lista, mindig a benne található elemek magassága méretűre fog nyúlni. Meg lehet még fűszerezni annyival, hogy a Separatorok magasságát is beleszámolja, illetve hogy legyen egy maximálisan engedett magassága is, én ezt nem tettem meg, de jó kiindulási alap.

 public class AutoHeightListView : ListView
    {
        public AutoHeightListView()
        {
        }

        protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);

            // ItemsSource változásakor 
            if (propertyName == nameof(ListView.ItemsSource))
            {
                if(ItemsSource != null)
                {
                    // Kikérjük a ListView feltemapltezett celljeit.
                    IEnumerable<PropertyInfo> pInfos = (this as ItemsView<Cell>).GetType().GetRuntimeProperties();
                    var templatedItems = pInfos.FirstOrDefault(info => info.Name == "TemplatedItems");

                    if (templatedItems != null)
                    {
                        var cells = templatedItems.GetValue(this);
                        if(cells is Xamarin.Forms.ITemplatedItemsList<Xamarin.Forms.Cell> cellsCasted)
                        {
                            if(cellsCasted.Count != 0)
                            {
                                ((ViewCell)cellsCasted.Last()).View.SizeChanged += FirstElementHeightChanged;
                            }
                        }
                    }
                }
            }
        }

        double prevHeight = 0;

        private void FirstElementHeightChanged(object sender, EventArgs e)
        {
            SetHeightRequestByCellsHeight();
        }

        /// <summary>
        /// Megméri minden sor Viewcell magasságát, és az egész listview magasságát ezeknek az összegére állítja be.
        /// </summary>
        private void SetHeightRequestByCellsHeight()
        {
            double calculatedHeight = 0;

            // Kikérjük a ListView feltemapltezett celljeit.
            IEnumerable<PropertyInfo> pInfos = (this as ItemsView<Cell>).GetType().GetRuntimeProperties();
            var templatedItems = pInfos.FirstOrDefault(info => info.Name == "TemplatedItems");

            if (templatedItems != null)
            {
                var cells = templatedItems.GetValue(this);
                foreach (ViewCell cell in cells as Xamarin.Forms.ITemplatedItemsList<Xamarin.Forms.Cell>)
                {
                    calculatedHeight += cell.View.Height;
                }
            }

            if (calculatedHeight == prevHeight)
                return;

            prevHeight = calculatedHeight;
            HeightRequest = calculatedHeight;
        }
    }
This content has 3 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.