summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/ElementTemplate.cs
blob: 016dee7ef92349891122de2be9fad764dcd71621 (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
using System;
using System.Collections.Generic;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms
{
#pragma warning disable 612
	public class ElementTemplate : IElement, IDataTemplate
#pragma warning restore 612
	{
		List<Action<object, ResourcesChangedEventArgs>> _changeHandlers;
		Element _parent;

		internal ElementTemplate()
		{
		}

		internal ElementTemplate(Type type) : this()
		{
			if (type == null)
				throw new ArgumentNullException("type");

			LoadTemplate = () => Activator.CreateInstance(type);
		}

		internal ElementTemplate(Func<object> loadTemplate) : this()
		{
			if (loadTemplate == null)
				throw new ArgumentNullException("loadTemplate");

			LoadTemplate = loadTemplate;
		}

		Func<object> LoadTemplate { get; set; }
#pragma warning disable 0612
		Func<object> IDataTemplate.LoadTemplate
		{
#pragma warning restore 0612
			get { return LoadTemplate; }
			set { LoadTemplate = value; }
		}

		void IElement.AddResourcesChangedListener(Action<object, ResourcesChangedEventArgs> onchanged)
		{
			_changeHandlers = _changeHandlers ?? new List<Action<object, ResourcesChangedEventArgs>>(1);
			_changeHandlers.Add(onchanged);
		}

		Element IElement.Parent
		{
			get { return _parent; }
			set
			{
				if (_parent == value)
					return;
				if (_parent != null)
					((IElement)_parent).RemoveResourcesChangedListener(OnResourcesChanged);
				_parent = value;
				if (_parent != null)
					((IElement)_parent).AddResourcesChangedListener(OnResourcesChanged);
			}
		}

		void IElement.RemoveResourcesChangedListener(Action<object, ResourcesChangedEventArgs> onchanged)
		{
			if (_changeHandlers == null)
				return;
			_changeHandlers.Remove(onchanged);
		}

		public object CreateContent()
		{
			if (LoadTemplate == null)
				throw new InvalidOperationException("LoadTemplate should not be null");
			if (this is DataTemplateSelector)
				throw new InvalidOperationException("Cannot call CreateContent directly on a DataTemplateSelector");

			object item = LoadTemplate();
			SetupContent(item);

			return item;
		}

		internal virtual void SetupContent(object item)
		{
		}

		void OnResourcesChanged(object sender, ResourcesChangedEventArgs e)
		{
			if (_changeHandlers == null)
				return;
			foreach (Action<object, ResourcesChangedEventArgs> handler in _changeHandlers)
				handler(this, e);
		}
	}
}