summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/Interactivity/BindingCondition.cs
blob: 1d111850b0d44e402a90187593820b26849283ba (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
using System;
using Xamarin.Forms.Xaml;

namespace Xamarin.Forms
{
	public sealed class BindingCondition : Condition, IValueProvider
	{
		readonly BindableProperty _boundProperty;

		BindingBase _binding;
		object _triggerValue;

		public BindingCondition()
		{
			_boundProperty = BindableProperty.CreateAttached("Bound", typeof(object), typeof(BindingCondition), null, propertyChanged: OnBoundPropertyChanged);
		}

		public BindingBase Binding
		{
			get { return _binding; }
			set
			{
				if (_binding == value)
					return;
				if (IsSealed)
					throw new InvalidOperationException("Can not change Binding once the Condition has been applied.");
				_binding = value;
			}
		}

		public object Value
		{
			get { return _triggerValue; }
			set
			{
				if (_triggerValue == value)
					return;
				if (IsSealed)
					throw new InvalidOperationException("Can not change Value once the Condition has been applied.");
				_triggerValue = value;
			}
		}

		internal IServiceProvider ServiceProvider { get; set; }

		internal IValueConverterProvider ValueConverter { get; set; }

		object IValueProvider.ProvideValue(IServiceProvider serviceProvider)
		{
			ValueConverter = serviceProvider.GetService(typeof(IValueConverterProvider)) as IValueConverterProvider;
			ServiceProvider = serviceProvider;

			return this;
		}

		internal override bool GetState(BindableObject bindable)
		{
			object newValue = bindable.GetValue(_boundProperty);
			return EqualsToValue(newValue);
		}

		internal override void SetUp(BindableObject bindable)
		{
			if (Binding != null)
				bindable.SetBinding(_boundProperty, Binding.Clone());
		}

		internal override void TearDown(BindableObject bindable)
		{
			bindable.RemoveBinding(_boundProperty);
			bindable.ClearValue(_boundProperty);
		}

		bool EqualsToValue(object other)
		{
			if ((other == Value) || (other != null && other.Equals(Value)))
				return true;

			object converted = null;
			if (ValueConverter != null)
				converted = ValueConverter.Convert(Value, other != null ? other.GetType() : typeof(object), null, ServiceProvider);
			else
				return false;

			return (other == converted) || (other != null && other.Equals(converted));
		}

		void OnBoundPropertyChanged(BindableObject bindable, object oldValue, object newValue)
		{
			bool oldState = EqualsToValue(oldValue);
			bool newState = EqualsToValue(newValue);

			if (newState == oldState)
				return;

			if (ConditionChanged != null)
				ConditionChanged(bindable, oldState, newState);
		}
	}
}