/
CompareStateTrigger.cs
87 lines (72 loc) · 1.92 KB
/
CompareStateTrigger.cs
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
using System;
using System.Globalization;
namespace Xamarin.Forms
{
public sealed class CompareStateTrigger : StateTriggerBase
{
public CompareStateTrigger()
{
UpdateState();
}
public object Property
{
get => GetValue(PropertyProperty);
set => SetValue(PropertyProperty, value);
}
public static readonly BindableProperty PropertyProperty =
BindableProperty.Create(nameof(Property), typeof(object), typeof(CompareStateTrigger), null,
propertyChanged: OnPropertyChanged);
static void OnPropertyChanged(BindableObject bindable, object oldvalue, object newvalue)
{
((CompareStateTrigger)bindable).UpdateState();
}
public object Value
{
get => GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
public static readonly BindableProperty ValueProperty =
BindableProperty.Create(nameof(Value), typeof(object), typeof(CompareStateTrigger), null,
propertyChanged: OnValueChanged);
static void OnValueChanged(BindableObject bindable, object oldvalue, object newvalue)
{
((CompareStateTrigger)bindable).UpdateState();
}
protected override void OnAttached()
{
base.OnAttached();
UpdateState();
}
void UpdateState()
{
SetActive(AreEqual(Property, Value));
}
bool AreEqual(object value1, object value2)
{
if (value1 == value2)
return true;
if (value1 != null && value2 != null)
return AreEqualType(value1, value2) || AreEqualType(value2, value1);
return false;
}
bool AreEqualType(object value1, object value2)
{
if (value2 is Enum)
value1 = ConvertToEnum(value2.GetType(), value1);
else
value1 = Convert.ChangeType(value1, value2.GetType(), CultureInfo.InvariantCulture);
return value2.Equals(value1);
}
object ConvertToEnum(Type enumType, object value)
{
try
{
return Enum.IsDefined(enumType, value) ? Enum.ToObject(enumType, value) : null;
}
catch
{
return null;
}
}
}
}