summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Issue1762.cs
blob: cc50fa5229626561cef3d26276265577d8f16b7f (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
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;

using Xamarin.Forms;
using System.Collections.Generic;

using Xamarin.Forms.CustomAttributes;

namespace Xamarin.Forms.Controls
{
	[Preserve (AllMembers=true)]
	[Issue (IssueTracker.Github, 1762, "Binding issue with SwitchCell - System.ArgumentException:'jobject' must not be IntPtr.Zero", PlatformAffected.Android)]
	public class Issue1762 : ContentPage
	{
		public static ObservableGroupMyObjCollection Objs = new ObservableGroupMyObjCollection ();

		public Issue1762 ()
		{
			StackLayout stack = new StackLayout
			{};
			stack.Children.Add (new ListView {
				ItemsSource = Objs,
				ItemTemplate = new DataTemplate (() => {
					SwitchCell cell = new SwitchCell ();
					cell.SetBinding<MyObj> (SwitchCell.TextProperty, m => m.DisplayText);
					cell.SetBinding<MyObj> (SwitchCell.OnProperty, m => m.IsSelected);
					return cell;
				}),
				IsGroupingEnabled = true,
				GroupDisplayBinding = new Binding ("Key")
			});
			Button b = new Button {
				Text = "add"
			};
			b.Clicked += (sender, e) => {
				Random r = new Random ();
				Objs.Add (new MyObj {
					DisplayText = r.Next ().ToString (),
					IsSelected = r.Next () % 2 == 0
				});
			};
			stack.Children.Add (b);

			Content = stack;
		}
	}

	public class Grouping<K, T> : ObservableCollection<T>, IGroupingCollection<K, T> where T : INotifyPropertyChanged
	{
		public K Key { get; private set; }

		public Grouping (K key, IEnumerable<T> items)
		{
			Key = key;
			foreach (var item in items)
				Items.Add (item);
		}

		public Grouping (K key, T item)
		{
			Key = key;
			Items.Add (item);
		}
	}

	public static class Extensions
	{
		public static IEnumerable<T> Enumerate<T> (this IEnumerable<IEnumerable<T>> listOfList)
		{
			foreach (var list in listOfList) {
				foreach (T item in list)
					yield return item;
			}
		}
	}

	public interface IGroupingCollection<K, T> : ICollection<T>, IGrouping<K, T> {}

	public interface ISortingKey<T>
	{
		T SortingKey { get; }
	}

	public class MyObj : ObservableObject, ISortingKey<bool>
	{
		public MyObj () {}

		string _displayText;

		public string DisplayText
		{
			get { return _displayText; }
			set { SetProperty (ref _displayText, value); }
		}

		bool _isSelected;

		public bool IsSelected
		{
			get { return _isSelected; }
			set
			{
				if (SetProperty (ref _isSelected, value))
					NotifyPropertyChanged (() => SortingKey);
			}
		}

		#region ISortingKey implementation
		public bool SortingKey
		{
			get { return IsSelected; }
		}
		#endregion
	}

	public abstract class ObservableGroupCollection<K, T> : ObservableCollection<IGroupingCollection<K, T>> where T : class, INotifyPropertyChanged, ISortingKey<K>
	{
		Func<K, K, bool> _equalityComparer;

		public ObservableGroupCollection (IEnumerable<IGroupingCollection<K, T>> items, Func<K, K, bool> equalityComparer)
			: base (items)
		{
			_equalityComparer = equalityComparer;
			if (items != null) {
				foreach (var propChangeItem in items.Enumerate ())
					SetupPropertyChanged (propChangeItem, equalityComparer);
			}
		}

		void SetupPropertyChanged (T propChangeItem, Func<K, K, bool> equalityComparer)
		{
			propChangeItem.PropertyChanged += (sender, e) => {
				if (e.PropertyName == "SortingKey") {
					//using (BlockReentrancy())
					{
						T changedItem = (T)sender;
						IGroupingCollection<K, T> oldGroup = null, newGroup = null;
						foreach (var group in Items) //go through all groups to find item
						{
							if (oldGroup == null /* || newGroup == null*/) {
								foreach (var item2 in group) {
									if (oldGroup == null && item2 == changedItem)
										oldGroup = group;
								}
							}
							if (newGroup == null && equalityComparer (group.Key, changedItem.SortingKey))
								newGroup = group;
						}
						if (oldGroup != null) {
							oldGroup.Remove (changedItem);
							if (oldGroup.Count == 0) {
								OnCollectionChanged (new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Remove, oldGroup));
								Items.Remove (oldGroup);
							}
						}
#if DEBUG
						else
							throw new Exception ("oldGroup == null");
#endif
						if (newGroup == null) {
							Items.Add (newGroup = new Grouping<K, T> (changedItem.SortingKey, changedItem));
							OnCollectionChanged (new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, newGroup));
						} else {
							foreach (var item in newGroup) {
								if (item == changedItem)
									return;
							}
							newGroup.Add (changedItem);
						}
					}
				}
			};
		}

		public ObservableGroupCollection (IGroupingCollection<K, T> item, Func<K, K, bool> equalityComparer)
		{
			_equalityComparer = equalityComparer;
			if (item != null) {
				foreach (T t in item)
					SetupPropertyChanged (t, equalityComparer);
			}
		}

		public void Add (T item)
		{
			SetupPropertyChanged (item, _equalityComparer);
			foreach (IGroupingCollection<K, T> group in Items) {
				if (_equalityComparer (group.Key, item.SortingKey)) {
					group.Add (item);
					return;
				}
			}
			Grouping<K, T> newGroup = new Grouping<K, T> (item.SortingKey, item);
			Items.Add (newGroup);
			OnCollectionChanged (new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, newGroup));
		}

		/*protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);
        }*/
	}

	public class ObservableGroupMyObjCollection : ObservableGroupCollection<bool, MyObj>
	{
		public ObservableGroupMyObjCollection ()
			: base ((IGroupingCollection<bool, MyObj>)null, (k1, k2) => k1 == k2) {}
	}

	public abstract class ObservableObject : INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;


		protected virtual void NotifyPropertyChanged ([CallerMemberName] string propertyName = null)
		{
			OnPropertyChanged (new PropertyChangedEventArgs (propertyName));
		}

		protected virtual void NotifyPropertyChanged<T> (Expression<Func<T>> propertyExpression)
		{
			string propertyName = GetPropertyName (propertyExpression);
			OnPropertyChanged (new PropertyChangedEventArgs (propertyName));
		}

		protected virtual void OnPropertyChanged (PropertyChangedEventArgs e)
		{
			var eventHandler = PropertyChanged;
			if (eventHandler != null) {
				try {
					eventHandler (this, e); //crashes here!
				} catch (Exception ex) {
					System.Diagnostics.Debug.WriteLine (ex);
				}
			}
		}


		protected bool SetProperty<T> (ref T storage, T value, Expression<Func<T>> propertyExpression)
		{
			var propertyName = GetPropertyName (propertyExpression);
			return SetProperty<T> (ref storage, value, propertyName);
		}


		protected bool SetProperty<T> (ref T storage, T value, [CallerMemberName] string propertyName = null)
		{
			if (EqualityComparer<T>.Default.Equals (storage, value))
				return false;

			storage = value;
			NotifyPropertyChanged (propertyName);
			return true;
		}

		string GetPropertyName<T> (Expression<Func<T>> propertyExpression)
		{
			if (propertyExpression == null)
				throw new ArgumentNullException ("propertyExpression");

			if (propertyExpression.Body.NodeType != ExpressionType.MemberAccess)
				throw new ArgumentException ("Should be a member access lambda expression", "propertyExpression");

			var memberExpression = (MemberExpression)propertyExpression.Body;
			return memberExpression.Member.Name;
		}
	}
}