summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/DataTemplate.cs
blob: 676718a04ade7a02dcc1329d0317bc44af8f9ec4 (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
using System;
using System.Collections.Generic;

namespace Xamarin.Forms
{
	public class DataTemplate : ElementTemplate
	{
		public DataTemplate()
		{
		}

		public DataTemplate(Type type) : base(type)
		{
		}

		public DataTemplate(Func<object> loadTemplate) : base(loadTemplate)
		{
		}

		public IDictionary<BindableProperty, BindingBase> Bindings { get; } = new Dictionary<BindableProperty, BindingBase>();

		public IDictionary<BindableProperty, object> Values { get; } = new Dictionary<BindableProperty, object>();

		public void SetBinding(BindableProperty property, BindingBase binding)
		{
			if (property == null)
				throw new ArgumentNullException("property");
			if (binding == null)
				throw new ArgumentNullException("binding");

			Values.Remove(property);
			Bindings[property] = binding;
		}

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

			Bindings.Remove(property);
			Values[property] = value;
		}

		internal override void SetupContent(object item)
		{
			ApplyBindings(item);
			ApplyValues(item);
		}

		void ApplyBindings(object item)
		{
			if (Bindings == null)
				return;

			var bindable = item as BindableObject;
			if (bindable == null)
				return;

			foreach (KeyValuePair<BindableProperty, BindingBase> kvp in Bindings)
			{
				if (Values.ContainsKey(kvp.Key))
					throw new InvalidOperationException("Binding and Value found for " + kvp.Key.PropertyName);

				bindable.SetBinding(kvp.Key, kvp.Value.Clone());
			}
		}

		void ApplyValues(object item)
		{
			if (Values == null)
				return;

			var bindable = item as BindableObject;
			if (bindable == null)
				return;
			foreach (KeyValuePair<BindableProperty, object> kvp in Values)
				bindable.SetValue(kvp.Key, kvp.Value);
		}
	}
}