summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/AddingMultipleItemsListView.cs
blob: 56a714acf2dd5bb8fad58be2372b6e5a1ef7ac0f (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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Windows.Input;

using Xamarin.Forms;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
#if UITEST
using NUnit.Framework;
using Xamarin.UITest;
#endif

namespace Xamarin.Forms.Controls
{
	public class PropertyChangedBase : INotifyPropertyChanged
	{
		Dictionary<string, object> _properties = new Dictionary<string, object>();

		protected T GetProperty<T>([CallerMemberName] string name = null)
		{
			object value = null;
			if (_properties.TryGetValue(name, out value)) {
				return value == null ? default(T) : (T)value;
			}
			return default(T);
		}

		protected void SetProperty<T>(T value, [CallerMemberName] string name = null)
		{
			if (Equals(value, GetProperty<T>(name))) {
				return;
			}
			_properties[name] = value;
			OnPropertyChanged(name);
		}

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null) {
				handler(this, new PropertyChangedEventArgs(propertyName));
			}
		}
	}

	public class ViewModelError
	{
		public ViewModelError(string text)
		{
			Text = text;
		}

		public string Text { get; set; }

		public override bool Equals(object obj)
		{
			var error = obj as ViewModelError;
			if (error == null) {
				return false;
			}
			return Text.Equals(error.Text);
		}

		public override int GetHashCode()
		{
			return Text.GetHashCode();
		}

		public override string ToString()
		{
			return string.Format("ViewModelError: {0}", Text);
		}
	}

	public class ViewModelBase : PropertyChangedBase
	{
		public ViewModelBase()
		{
			_errors = new List<ViewModelError>();
			Validate();
		}

		readonly List<ViewModelError> _errors;

		public virtual bool IsValid
		{
			get { return _errors.Count <= 0; }
		}
			
		protected IEnumerable<ViewModelError> Errors
		{
			get { return _errors; }
		}

		public event EventHandler IsValidChanged;

		public event EventHandler IsBusyChanged;

		protected virtual void Validate()
		{
			OnPropertyChanged("IsValid");
			OnPropertyChanged("Errors");

			var callback = IsValidChanged;
			if (callback != null) {
				callback(this, EventArgs.Empty);
			}

			// Spit out errors for easier debugging.
			if (_errors != null && _errors.Count > 0) {
				Debug.WriteLine("Errors:");
				foreach (var error in _errors) {
					Debug.WriteLine(error);
				}
			}
		}
			
		protected virtual void ValidateProperty(Func<bool> validate, ViewModelError error)
		{
			if (validate()) {
				_errors.Remove(error);
			} else if (!_errors.Contains(error)) {
				_errors.Add(error);
			}
		}

		public virtual bool IsBusy
		{
			get { return _isBusy; }
			set
			{
				if (_isBusy != value) {
					_isBusy = value;
					OnPropertyChanged("IsBusy");
					OnIsBusyChanged();
				}
			}
		}

		bool _isBusy = false;

		protected virtual void OnIsBusyChanged()
		{
			// Some models might want to have a validation thet depends on the busy state.
			Validate();
			var method = IsBusyChanged;
			if (method != null)
				IsBusyChanged(this, EventArgs.Empty);
		}
	}

	public class DelegateCommand : ICommand
	{
		readonly Predicate<object> _canExecute;
		readonly Action<object> _execute;

		public event EventHandler CanExecuteChanged;

		public DelegateCommand(Action<object> execute)
			: this(execute, null)
		{
		}

		public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
		{
			_execute = execute;
			_canExecute = canExecute;
		}

		public bool CanExecute(object parameter)
		{
			if (_canExecute == null) {
				return true;
			}

			return _canExecute(parameter);
		}

		public void Execute(object parameter)
		{
			_execute(parameter);
		}

		public void RaiseCanExecuteChanged()
		{
			var handler = CanExecuteChanged;
			if (handler != null) {
				handler(this, EventArgs.Empty);
			}
		}
	}

	[Preserve (AllMembers = true)]
	public class ExampleViewModel : ViewModelBase
	{
		[Preserve (AllMembers = true)]
		public class Job : ViewModelBase
		{

			public string JobId
			{
				get { return GetProperty<string>(); }
				set { SetProperty(value); }
			}

			public string JobName
			{
				get { return GetProperty<string>(); }
				set { SetProperty(value); }
			}

			public double? Hours
			{
				get { return GetProperty<double?>(); }
				set { SetProperty(value); }
			}

			public bool Locked
			{
				get { return GetProperty<bool>(); }
				set { SetProperty(value); }
			}
		}
				
		public ExampleViewModel()
		{

			Jobs = new ObservableCollection<Job>()
			{
				new Job() { JobId = "3672", JobName = "Big Job", Hours = 2},
				new Job() { JobId = "6289", JobName = "Smaller Job", Hours = 2},
				new Job() { JobId = "3672-41", JobName = "Add On Job", Hours = 23},                
			};            
		}

		public ObservableCollection<Job> Jobs { get; set; }


		public ICommand AddOneCommand
		{
			get
			{
				if (_addOneCommand == null) {
					_addOneCommand = new DelegateCommand(obj => {
						Jobs.Add(new Job(){JobId = "1234", JobName = "add one", Hours = 12});                        
						}, obj => !IsBusy);
				}
				return _addOneCommand;
			}
		}

		ICommand _addOneCommand;

		public ICommand AddTwoCommand
		{
			get
			{
				if (_addTwoCommand == null) {
					_addTwoCommand = new DelegateCommand(obj => {
							Jobs.Add(new Job() { JobId = "9999", JobName = "add two", Hours = 12 });
							Jobs.Add(new Job() { JobId = "8888", JobName = "add two", Hours = 12 });
						}, obj => !IsBusy);
				}
				return _addTwoCommand;
			}
		}

		ICommand _addTwoCommand;

		public void GetHours()
		{
		
			var results = new ObservableCollection<Job>()
			{
				new Job() { JobId = "3672", JobName = "RADO", Hours = 2},
				new Job() { JobId = "6289", JobName = "MGA Life Cycle Flexible Test System", Hours = 2},

			};

			foreach (var x in results)
				Jobs.Add(x);

		}
	}

	public class DoubleStringConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (null == value || "0" == value.ToString())
				return string.Empty;
			return value.ToString();
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			double? returnValue = null;
			double convertResult;
			var strvalue = value as string;
			if (double.TryParse(strvalue, out convertResult))
			{
				returnValue = convertResult;
			}
			return returnValue;
		}
	}

	
}

namespace Xamarin.Forms.Controls.Issues
{
	[Preserve(AllMembers = true)]
	[Issue(IssueTracker.None, 0, "Adding Multiple Items to a ListView", PlatformAffected.All)]
	public class AddingMultipleItemsListView : TestContentPage
	{
		protected override void Init()
		{
			Title = "Hours";
			var exampleViewModel = new ExampleViewModel();
			BindingContext = exampleViewModel;

			var listView = new ListView
			{
				ItemTemplate = new DataTemplate(typeof(CustomViewCell)),
				HeightRequest = 400,
				VerticalOptions = LayoutOptions.Start
			};

			listView.SetBinding(ListView.ItemsSourceProperty, new Binding("Jobs", BindingMode.TwoWay));

			var addOneJobButton = new Button
			{
				Text = "Add One"
			};
			addOneJobButton.SetBinding(Button.CommandProperty, new Binding("AddOneCommand"));

			var addTwoJobsButton = new Button
			{
				Text = "Add Two"
			};
			addTwoJobsButton.SetBinding(Button.CommandProperty, new Binding("AddTwoCommand"));

			var layout = new StackLayout
			{
				Orientation = StackOrientation.Vertical,
				VerticalOptions = LayoutOptions.StartAndExpand,
				Spacing = 15,
				Children = {
					listView,
					addOneJobButton,
					addTwoJobsButton
				}
			};
			Content = layout;
		}

		[Preserve(AllMembers = true)]
		public class CustomViewCell : ViewCell
		{
			public CustomViewCell()
			{
				var jobId = new Label
				{
#pragma warning disable 618
					Font = Font.SystemFontOfSize(20),
#pragma warning restore 618
					WidthRequest = 105,
					VerticalOptions = LayoutOptions.Center,

					HorizontalOptions = LayoutOptions.StartAndExpand
				};
				jobId.SetBinding(Label.TextProperty, "JobId");

				var jobName = new Label
				{
					VerticalOptions = LayoutOptions.Center,
					WidthRequest = 175,
					HorizontalOptions = LayoutOptions.CenterAndExpand,
				};
				jobName.SetBinding(Label.TextProperty, "JobName");

				var hours = new Label
				{
					WidthRequest = 45,
					VerticalOptions = LayoutOptions.Center,
#pragma warning disable 618
					XAlign = TextAlignment.End,
#pragma warning restore 618
					HorizontalOptions = LayoutOptions.EndAndExpand,

				};
				hours.SetBinding(Label.TextProperty, new Binding("Hours", BindingMode.OneWay, new DoubleStringConverter()));

				var hlayout = new StackLayout
				{
					Children = {
						jobId,
						jobName,
						hours
					},
					Orientation = StackOrientation.Horizontal,
				};

				View = hlayout;
			}
		}

#if UITEST
		[Test]
		public void AddingMultipleListViewTests1AllElementsPresent()
		{
			RunningApp.WaitForElement(q => q.Marked("Big Job"));
			RunningApp.WaitForElement(q => q.Marked("Smaller Job"));
			RunningApp.WaitForElement(q => q.Marked("Add On Job"));
			RunningApp.WaitForElement(q => q.Marked("Add One"));
			RunningApp.WaitForElement(q => q.Marked("Add Two"));
			RunningApp.WaitForElement(q => q.Marked("3672"));
			RunningApp.WaitForElement(q => q.Marked("6289"));
			RunningApp.WaitForElement(q => q.Marked("3672-41"));
			RunningApp.WaitForElement(q => q.Marked("2"));
			RunningApp.WaitForElement(q => q.Marked("2"));
			RunningApp.WaitForElement(q => q.Marked("23"));

			RunningApp.Screenshot("All elements are present");
		}

		[Test]
		public void AddingMultipleListViewTests2AddOneElementToList()
		{
			RunningApp.Tap(q => q.Marked("Add One"));

			RunningApp.WaitForElement(q => q.Marked("1234"), timeout: TimeSpan.FromSeconds(2));
			RunningApp.Screenshot("One more element exists");
		}

		[Test]
		public void AddingMultipleListViewTests3AddTwoElementToList()
		{
			RunningApp.Screenshot("Click 'Add Two'");
			RunningApp.Tap(q => q.Marked("Add Two"));

			RunningApp.WaitForElement(q => q.Marked("9999"), timeout: TimeSpan.FromSeconds(2));
			RunningApp.WaitForElement(q => q.Marked("8888"), timeout: TimeSpan.FromSeconds(2));
			RunningApp.Screenshot("Two more element exist");
		}
#endif
	}
}