summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/Interactivity/MultiCondition.cs
blob: 1a80190abf00070c1da973759317a1c22fab56e9 (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
using System.Collections.Generic;

namespace Xamarin.Forms
{
	internal sealed class MultiCondition : Condition
	{
		readonly BindableProperty _aggregatedStateProperty;

		public MultiCondition()
		{
			_aggregatedStateProperty = BindableProperty.CreateAttached("AggregatedState", typeof(bool), typeof(MultiCondition), false, propertyChanged: OnAggregatedStatePropertyChanged);
			Conditions = new TriggerBase.SealedList<Condition>();
		}

		public IList<Condition> Conditions { get; }

		internal override bool GetState(BindableObject bindable)
		{
			return (bool)bindable.GetValue(_aggregatedStateProperty);
		}

		internal override void OnSealed()
		{
			((TriggerBase.SealedList<Condition>)Conditions).IsReadOnly = true;
			foreach (Condition condition in Conditions)
				condition.ConditionChanged = OnConditionChanged;
		}

		internal override void SetUp(BindableObject bindable)
		{
			foreach (Condition condition in Conditions)
				condition.SetUp(bindable);
		}

		internal override void TearDown(BindableObject bindable)
		{
			foreach (Condition condition in Conditions)
				condition.TearDown(bindable);
		}

		void OnAggregatedStatePropertyChanged(BindableObject bindable, object oldValue, object newValue)
		{
			if ((bool)oldValue == (bool)newValue)
				return;

			if (ConditionChanged != null)
				ConditionChanged(bindable, (bool)oldValue, (bool)newValue);
		}

		void OnConditionChanged(BindableObject bindable, bool oldValue, bool newValue)
		{
			var oldState = (bool)bindable.GetValue(_aggregatedStateProperty);
			var newState = true;
			foreach (Condition condition in Conditions)
			{
				if (!condition.GetState(bindable))
				{
					newState = false;
					break;
				}
			}
			if (newState != oldState)
				bindable.SetValue(_aggregatedStateProperty, newState);
		}
	}
}