summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Issue1875.cs
blob: 09e5eca4d3756b6035bed2f4c94c6ff5462af4ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms.CustomAttributes;

namespace Xamarin.Forms.Controls
{
	[Preserve (AllMembers=true)]
	[Issue (IssueTracker.Github, 1875, "NSRangeException adding items through ItemAppearing", PlatformAffected.iOS)]
	public class Issue1875
		: ContentPage
	{
		public Issue1875()
		{
			Button loadData = new Button { Text = "Load", HorizontalOptions = LayoutOptions.FillAndExpand };
			ListView mainList = new ListView {
				VerticalOptions = LayoutOptions.FillAndExpand,
				HorizontalOptions = LayoutOptions.FillAndExpand
			};

			mainList.SetBinding (ListView.ItemsSourceProperty, "Items");

			_viewModel = new MainViewModel ();
			BindingContext = _viewModel;
			loadData.Clicked += async (sender, e) => {
				await LoadData ();
			};

			mainList.ItemAppearing += OnItemAppearing;

			Content = new StackLayout {
				Children = {
					loadData,
					mainList
				}
			};
		}

		readonly MainViewModel _viewModel;
		int _start = 0;
		const int NumberOfRecords = 15;

		async void OnItemAppearing(object sender, ItemVisibilityEventArgs e)
		{
			var item = (int)e.Item;
			if (!_viewModel.IsLoading && item == _viewModel.Items.Last())
				await LoadData();
		}

		async Task LoadData ()
		{
			await _viewModel.LoadData (_start, NumberOfRecords);
			_start = _start + NumberOfRecords;
		}

		public class MainViewModel : INotifyPropertyChanged
		{
			public event PropertyChangedEventHandler PropertyChanged;

			public MainViewModel ()
			{
			}

			ObservableCollection<int> _items;
			public ObservableCollection<int> Items {
				get {
					if (_items == null)
						_items = new ObservableCollection<int> ();

					return _items;
				}
				set {
					_items = value;
					PropertyChanged (this, new PropertyChangedEventArgs ("Items"));
				}
			}

			bool _isLoading;
			public bool IsLoading {
				get {
					return _isLoading;
				}
				set {
					if (_isLoading != value) {
						_isLoading = value;
						PropertyChanged (this, new PropertyChangedEventArgs ("IsLoading"));
					}
				}
			}

#pragma warning disable 1998 // considered for removal
			public async Task LoadData (int start, int numberOfRecords)
#pragma warning restore 1998
			{
				IsLoading = true;
				for (int counter = 0; counter < numberOfRecords; counter++)
					Items.Add (start + counter);

				IsLoading = false;
			}
		}
	}
}