summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/BindableObject.cs
blob: d45580f829a1d557df47b267b378c393e9226583 (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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms
{
	public abstract class BindableObject : INotifyPropertyChanged, IDynamicResourceHandler
	{
		public static readonly BindableProperty BindingContextProperty =
			BindableProperty.Create("BindingContext", typeof(object), typeof(BindableObject), default(object),
									BindingMode.OneWay, null, BindingContextPropertyChanged, null, null, BindingContextPropertyBindingChanging);

		readonly List<BindablePropertyContext> _properties = new List<BindablePropertyContext>(4);

		bool _applying;
		object _inheritedContext;

		public object BindingContext
		{
			get { return _inheritedContext ?? GetValue(BindingContextProperty); }
			set { SetValue(BindingContextProperty, value); }
		}

		void IDynamicResourceHandler.SetDynamicResource(BindableProperty property, string key)
		{
			SetDynamicResource(property, key, false);
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public event EventHandler BindingContextChanged;

		public void ClearValue(BindableProperty property)
		{
			ClearValue(property, true);
		}

		public void ClearValue(BindablePropertyKey propertyKey)
		{
			if (propertyKey == null)
				throw new ArgumentNullException("propertyKey");

			ClearValue(propertyKey.BindableProperty, false);
		}

		public object GetValue(BindableProperty property)
		{
			if (property == null)
				throw new ArgumentNullException("property");

			BindablePropertyContext context = property.DefaultValueCreator != null ? GetOrCreateContext(property) : GetContext(property);

			if (context == null)
				return property.DefaultValue;

			return context.Value;
		}

		public event PropertyChangingEventHandler PropertyChanging;

		public void RemoveBinding(BindableProperty property)
		{
			if (property == null)
				throw new ArgumentNullException("property");

			BindablePropertyContext context = GetContext(property);
			if (context == null || context.Binding == null)
				return;

			RemoveBinding(property, context);
		}

		public void SetBinding(BindableProperty targetProperty, BindingBase binding)
		{
			SetBinding(targetProperty, binding, false);
		}

		public void SetValue(BindableProperty property, object value)
		{
			SetValue(property, value, false, true);
		}

		public void SetValue(BindablePropertyKey propertyKey, object value)
		{
			if (propertyKey == null)
				throw new ArgumentNullException("propertyKey");

			SetValue(propertyKey.BindableProperty, value, false, false);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static void SetInheritedBindingContext(BindableObject bindable, object value)
		{
			BindablePropertyContext bpContext = bindable.GetContext(BindingContextProperty);
			if (bpContext != null && ((bpContext.Attributes & BindableContextAttributes.IsManuallySet) != 0))
				return;

			object oldContext = bindable._inheritedContext;

			if (ReferenceEquals(oldContext, value))
				return;

			if (bpContext != null && oldContext == null)
				oldContext = bpContext.Value;

			if (bpContext != null && bpContext.Binding != null)
			{
				bpContext.Binding.Context = value;
				bindable._inheritedContext = null;
			}
			else
			{
				bindable._inheritedContext = value;
			}

			bindable.ApplyBindings();
			bindable.OnBindingContextChanged();
		}

		protected void ApplyBindings()
		{
			ApplyBindings(false);
		}

		protected virtual void OnBindingContextChanged()
		{
			BindingContextChanged?.Invoke(this, EventArgs.Empty);
		}

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

		protected virtual void OnPropertyChanging([CallerMemberName] string propertyName = null)
		{
			PropertyChangingEventHandler changing = PropertyChanging;
			if (changing != null)
				changing(this, new PropertyChangingEventArgs(propertyName));
		}

		protected void UnapplyBindings()
		{
			for (int i = 0, _propertiesCount = _properties.Count; i < _propertiesCount; i++) {
				BindablePropertyContext context = _properties [i];
				if (context.Binding == null)
					continue;

				context.Binding.Unapply();
			}
		}

		internal bool GetIsBound(BindableProperty targetProperty)
		{
			if (targetProperty == null)
				throw new ArgumentNullException("targetProperty");

			BindablePropertyContext bpcontext = GetContext(targetProperty);
			return bpcontext != null && bpcontext.Binding != null;
		}

		internal bool GetIsDefault(BindableProperty targetProperty)
		{
			if (targetProperty == null)
				throw new ArgumentNullException(nameof(targetProperty));

			return GetContext(targetProperty) == null;
		}

		internal object[] GetValues(BindableProperty property0, BindableProperty property1)
		{
			var values = new object[2];

			for (var i = 0; i < _properties.Count; i++)
			{
				BindablePropertyContext context = _properties[i];

				if (ReferenceEquals(context.Property, property0))
				{
					values[0] = context.Value;
					property0 = null;
				}
				else if (ReferenceEquals(context.Property, property1))
				{
					values[1] = context.Value;
					property1 = null;
				}

				if (property0 == null && property1 == null)
					return values;
			}

			if (!ReferenceEquals(property0, null))
				values[0] = property0.DefaultValueCreator == null ? property0.DefaultValue : CreateAndAddContext(property0).Value;
			if (!ReferenceEquals(property1, null))
				values[1] = property1.DefaultValueCreator == null ? property1.DefaultValue : CreateAndAddContext(property1).Value;

			return values;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public object[] GetValues(BindableProperty property0, BindableProperty property1, BindableProperty property2)
		{
			var values = new object[3];

			for (var i = 0; i < _properties.Count; i++)
			{
				BindablePropertyContext context = _properties[i];

				if (ReferenceEquals(context.Property, property0))
				{
					values[0] = context.Value;
					property0 = null;
				}
				else if (ReferenceEquals(context.Property, property1))
				{
					values[1] = context.Value;
					property1 = null;
				}
				else if (ReferenceEquals(context.Property, property2))
				{
					values[2] = context.Value;
					property2 = null;
				}

				if (property0 == null && property1 == null && property2 == null)
					return values;
			}

			if (!ReferenceEquals(property0, null))
				values[0] = property0.DefaultValueCreator == null ? property0.DefaultValue : CreateAndAddContext(property0).Value;
			if (!ReferenceEquals(property1, null))
				values[1] = property1.DefaultValueCreator == null ? property1.DefaultValue : CreateAndAddContext(property1).Value;
			if (!ReferenceEquals(property2, null))
				values[2] = property2.DefaultValueCreator == null ? property2.DefaultValue : CreateAndAddContext(property2).Value;

			return values;
		}

		internal virtual void OnRemoveDynamicResource(BindableProperty property)
		{
		}

		internal virtual void OnSetDynamicResource(BindableProperty property, string key)
		{
		}

		internal void RemoveDynamicResource(BindableProperty property)
		{
			if (property == null)
				throw new ArgumentNullException("property");

			OnRemoveDynamicResource(property);
			BindablePropertyContext context = GetOrCreateContext(property);
			context.Attributes &= ~BindableContextAttributes.IsDynamicResource;
		}

		internal void SetBinding(BindableProperty targetProperty, BindingBase binding, bool fromStyle)
		{
			if (targetProperty == null)
				throw new ArgumentNullException("targetProperty");
			if (binding == null)
				throw new ArgumentNullException("binding");

			BindablePropertyContext context = null;
			if (fromStyle && (context = GetContext(targetProperty)) != null && (context.Attributes & BindableContextAttributes.IsDefaultValue) == 0 &&
				(context.Attributes & BindableContextAttributes.IsSetFromStyle) == 0)
				return;

			context = context ?? GetOrCreateContext(targetProperty);
			if (fromStyle)
				context.Attributes |= BindableContextAttributes.IsSetFromStyle;
			else
				context.Attributes &= ~BindableContextAttributes.IsSetFromStyle;

			if (context.Binding != null)
				context.Binding.Unapply();

			BindingBase oldBinding = context.Binding;
			context.Binding = binding;

			if (targetProperty.BindingChanging != null)
				targetProperty.BindingChanging(this, oldBinding, binding);

			binding.Apply(BindingContext, this, targetProperty);
		}

		internal void SetDynamicResource(BindableProperty property, string key)
		{
			SetDynamicResource(property, key, false);
		}

		internal void SetDynamicResource(BindableProperty property, string key, bool fromStyle)
		{
			if (property == null)
				throw new ArgumentNullException(nameof(property));
			if (string.IsNullOrEmpty(key))
				throw new ArgumentNullException(nameof(key));

			BindablePropertyContext context = null;
			if (fromStyle && (context = GetContext(property)) != null && (context.Attributes & BindableContextAttributes.IsDefaultValue) == 0 &&
				(context.Attributes & BindableContextAttributes.IsSetFromStyle) == 0)
				return;

			context = context ?? GetOrCreateContext(property);

			context.Attributes |= BindableContextAttributes.IsDynamicResource;
			if (fromStyle)
				context.Attributes |= BindableContextAttributes.IsSetFromStyle;
			else
				context.Attributes &= ~BindableContextAttributes.IsSetFromStyle;

			OnSetDynamicResource(property, key);
		}

		internal void SetValue(BindableProperty property, object value, bool fromStyle)
		{
			SetValue(property, value, fromStyle, true);
		}

		internal void SetValueCore(BindablePropertyKey propertyKey, object value, SetValueFlags attributes = SetValueFlags.None)
		{
			SetValueCore(propertyKey.BindableProperty, value, attributes, SetValuePrivateFlags.None);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public void SetValueCore(BindableProperty property, object value, SetValueFlags attributes = SetValueFlags.None)
		{
			SetValueCore(property, value, attributes, SetValuePrivateFlags.Default);
		}

		internal void SetValueCore(BindableProperty property, object value, SetValueFlags attributes, SetValuePrivateFlags privateAttributes)
		{
			bool checkAccess = (privateAttributes & SetValuePrivateFlags.CheckAccess) != 0;
			bool manuallySet = (privateAttributes & SetValuePrivateFlags.ManuallySet) != 0;
			bool silent = (privateAttributes & SetValuePrivateFlags.Silent) != 0;
			bool fromStyle = (privateAttributes & SetValuePrivateFlags.FromStyle) != 0;
			bool converted = (privateAttributes & SetValuePrivateFlags.Converted) != 0;

			if (property == null)
				throw new ArgumentNullException("property");
			if (checkAccess && property.IsReadOnly)
			{
				Debug.WriteLine("Can not set the BindableProperty \"{0}\" because it is readonly.", property.PropertyName);
				return;
			}

			if (!converted && !property.TryConvert(ref value))
			{
				Log.Warning("SetValue", "Can not convert {0} to type '{1}'", value, property.ReturnType);
				return;
			}

			if (property.ValidateValue != null && !property.ValidateValue(this, value))
				throw new ArgumentException("Value was an invalid value for " + property.PropertyName, "value");

			if (property.CoerceValue != null)
				value = property.CoerceValue(this, value);

			BindablePropertyContext context = GetOrCreateContext(property);
			if (manuallySet) {
				context.Attributes |= BindableContextAttributes.IsManuallySet;
				context.Attributes &= ~BindableContextAttributes.IsSetFromStyle;
			} else
				context.Attributes &= ~BindableContextAttributes.IsManuallySet;

			if (fromStyle)
				context.Attributes |= BindableContextAttributes.IsSetFromStyle;
			// else omitted on purpose

			bool currentlyApplying = _applying;

			if ((context.Attributes & BindableContextAttributes.IsBeingSet) != 0)
			{
				Queue<SetValueArgs> delayQueue = context.DelayedSetters;
				if (delayQueue == null)
					context.DelayedSetters = delayQueue = new Queue<SetValueArgs>();

				delayQueue.Enqueue(new SetValueArgs(property, context, value, currentlyApplying, attributes));
			}
			else
			{
				context.Attributes |= BindableContextAttributes.IsBeingSet;
				SetValueActual(property, context, value, currentlyApplying, attributes, silent);

				Queue<SetValueArgs> delayQueue = context.DelayedSetters;
				if (delayQueue != null)
				{
					while (delayQueue.Count > 0)
					{
						SetValueArgs s = delayQueue.Dequeue();
						SetValueActual(s.Property, s.Context, s.Value, s.CurrentlyApplying, s.Attributes);
					}

					context.DelayedSetters = null;
				}

				context.Attributes &= ~BindableContextAttributes.IsBeingSet;
			}
		}

		void ApplyBindings(bool skipBindingContext)
		{
			var prop = _properties.ToArray();
			for (int i = 0, propLength = prop.Length; i < propLength; i++) {
				BindablePropertyContext context = prop [i];
				BindingBase binding = context.Binding;
				if (binding == null)
					continue;

				if (skipBindingContext && ReferenceEquals(context.Property, BindingContextProperty))
					continue;

				binding.Unapply();
				binding.Apply(BindingContext, this, context.Property);
			}
		}

		static void BindingContextPropertyBindingChanging(BindableObject bindable, BindingBase oldBindingBase, BindingBase newBindingBase)
		{
			object context = bindable._inheritedContext;
			var oldBinding = oldBindingBase as Binding;
			var newBinding = newBindingBase as Binding;

			if (context == null && oldBinding != null)
				context = oldBinding.Context;
			if (context != null && newBinding != null)
				newBinding.Context = context;
		}

		static void BindingContextPropertyChanged(BindableObject bindable, object oldvalue, object newvalue)
		{
			bindable._inheritedContext = null;
			bindable.ApplyBindings(true);
			bindable.OnBindingContextChanged();
		}

		void ClearValue(BindableProperty property, bool checkaccess)
		{
			if (property == null)
				throw new ArgumentNullException("property");

			if (checkaccess && property.IsReadOnly)
				throw new InvalidOperationException(string.Format("The BindableProperty \"{0}\" is readonly.", property.PropertyName));

			BindablePropertyContext bpcontext = GetContext(property);
			if (bpcontext == null)
				return;

			object original = bpcontext.Value;

			object newValue = property.GetDefaultValue(this);

			bool same = Equals(original, newValue);
			if (!same)
			{
				if (property.PropertyChanging != null)
					property.PropertyChanging(this, original, newValue);

				OnPropertyChanging(property.PropertyName);
			}

			bpcontext.Attributes &= ~BindableContextAttributes.IsManuallySet;
			bpcontext.Value = newValue;
			bpcontext.Attributes |= BindableContextAttributes.IsDefaultValue;

			if (!same)
			{
				OnPropertyChanged(property.PropertyName);
				if (property.PropertyChanged != null)
					property.PropertyChanged(this, original, newValue);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		BindablePropertyContext CreateAndAddContext(BindableProperty property)
		{
			var context = new BindablePropertyContext { Property = property, Value = property.DefaultValueCreator != null ? property.DefaultValueCreator(this) : property.DefaultValue };

			if (property.DefaultValueCreator != null)
				context.Attributes = BindableContextAttributes.IsDefaultValue;

			_properties.Add(context);
			return context;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		BindablePropertyContext GetContext(BindableProperty property)
		{
			List<BindablePropertyContext> properties = _properties;

			for (var i = 0; i < properties.Count; i++)
			{
				BindablePropertyContext context = properties[i];
				if (ReferenceEquals(context.Property, property))
					return context;
			}

			return null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		BindablePropertyContext GetOrCreateContext(BindableProperty property)
		{
			BindablePropertyContext context = GetContext(property);
			if (context == null)
			{
				context = CreateAndAddContext(property);
			}

			return context;
		}

		void RemoveBinding(BindableProperty property, BindablePropertyContext context)
		{
			context.Binding.Unapply();

			if (property.BindingChanging != null)
				property.BindingChanging(this, context.Binding, null);

			context.Binding = null;
		}

		void SetValue(BindableProperty property, object value, bool fromStyle, bool checkAccess)
		{
			if (property == null)
				throw new ArgumentNullException("property");

			if (checkAccess && property.IsReadOnly)
				throw new InvalidOperationException(string.Format("The BindableProperty \"{0}\" is readonly.", property.PropertyName));

			BindablePropertyContext context = null;
			if (fromStyle && (context = GetContext(property)) != null && (context.Attributes & BindableContextAttributes.IsDefaultValue) == 0 &&
				(context.Attributes & BindableContextAttributes.IsSetFromStyle) == 0)
				return;

			SetValueCore(property, value, SetValueFlags.ClearOneWayBindings | SetValueFlags.ClearDynamicResource,
				(fromStyle ? SetValuePrivateFlags.FromStyle : SetValuePrivateFlags.ManuallySet) | (checkAccess ? SetValuePrivateFlags.CheckAccess : 0));
		}

		void SetValueActual(BindableProperty property, BindablePropertyContext context, object value, bool currentlyApplying, SetValueFlags attributes, bool silent = false)
		{
			object original = context.Value;
			bool raiseOnEqual = (attributes & SetValueFlags.RaiseOnEqual) != 0;
			bool clearDynamicResources = (attributes & SetValueFlags.ClearDynamicResource) != 0;
			bool clearOneWayBindings = (attributes & SetValueFlags.ClearOneWayBindings) != 0;
			bool clearTwoWayBindings = (attributes & SetValueFlags.ClearTwoWayBindings) != 0;

			bool same = Equals(value, original);
			if (!silent && (!same || raiseOnEqual))
			{
				if (property.PropertyChanging != null)
					property.PropertyChanging(this, original, value);

				OnPropertyChanging(property.PropertyName);
			}

			if (!same || raiseOnEqual)
			{
				context.Value = value;
			}

			context.Attributes &= ~BindableContextAttributes.IsDefaultValue;

			if ((context.Attributes & BindableContextAttributes.IsDynamicResource) != 0 && clearDynamicResources)
				RemoveDynamicResource(property);

			BindingBase binding = context.Binding;
			if (binding != null)
			{
				if (clearOneWayBindings && binding.GetRealizedMode(property) == BindingMode.OneWay || clearTwoWayBindings && binding.GetRealizedMode(property) == BindingMode.TwoWay)
				{
					RemoveBinding(property, context);
					binding = null;
				}
			}

			if (!silent && (!same || raiseOnEqual))
			{
				if (binding != null && !currentlyApplying)
				{
					_applying = true;
					binding.Apply(true);
					_applying = false;
				}

				OnPropertyChanged(property.PropertyName);

				if (property.PropertyChanged != null)
					property.PropertyChanged(this, original, value);
			}
		}

		[Flags]
		enum BindableContextAttributes
		{
			IsManuallySet = 1 << 0,
			IsBeingSet = 1 << 1,
			IsDynamicResource = 1 << 2,
			IsSetFromStyle = 1 << 3,
			IsDefaultValue = 1 << 4
		}

		class BindablePropertyContext
		{
			public BindableContextAttributes Attributes;
			public BindingBase Binding;
			public Queue<SetValueArgs> DelayedSetters;
			public BindableProperty Property;
			public object Value;
		}

		[Flags]
		internal enum SetValuePrivateFlags
		{
			None = 0,
			CheckAccess = 1 << 0,
			Silent = 1 << 1,
			ManuallySet = 1 << 2,
			FromStyle = 1 << 3,
			Converted = 1 << 4,
			Default = CheckAccess
		}

		class SetValueArgs
		{
			public readonly SetValueFlags Attributes;
			public readonly BindablePropertyContext Context;
			public readonly bool CurrentlyApplying;
			public readonly BindableProperty Property;
			public readonly object Value;

			public SetValueArgs(BindableProperty property, BindablePropertyContext context, object value, bool currentlyApplying, SetValueFlags attributes)
			{
				Property = property;
				Context = context;
				Value = value;
				CurrentlyApplying = currentlyApplying;
				Attributes = attributes;
			}
		}
	}

	namespace Internals
	{
		[Flags]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public enum SetValueFlags
		{
			None = 0,
			ClearOneWayBindings = 1 << 0,
			ClearTwoWayBindings = 1 << 1,
			ClearDynamicResource = 1 << 2,
			RaiseOnEqual = 1 << 3
		}
	}
}