summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.WinRT/BackgroundTracker.cs
blob: c74740153a161d40255a707b1efbbce287945d47 (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
using System;
using System.ComponentModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

#if WINDOWS_UWP

namespace Xamarin.Forms.Platform.UWP
#else

namespace Xamarin.Forms.Platform.WinRT
#endif
{
	internal sealed class BackgroundTracker<T> : VisualElementTracker<Page, T> where T : FrameworkElement
	{
		readonly DependencyProperty _backgroundProperty;
		bool _backgroundNeedsUpdate = true;

		public BackgroundTracker(DependencyProperty backgroundProperty)
		{
			if (backgroundProperty == null)
				throw new ArgumentNullException("backgroundProperty");

			_backgroundProperty = backgroundProperty;
		}

		protected override void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName || e.PropertyName == Page.BackgroundImageProperty.PropertyName)
			{
				UpdateBackground();
			}

			base.OnPropertyChanged(sender, e);
		}

		protected override void UpdateNativeControl()
		{
			base.UpdateNativeControl();

			if (_backgroundNeedsUpdate)
				UpdateBackground();
		}

		void UpdateBackground()
		{
			if (Element == null)
				return;

			FrameworkElement element = Control ?? Container;
			if (element == null)
				return;

			string backgroundImage = Element.BackgroundImage;
			if (backgroundImage != null)
			{
				Uri uri;
				if (!Uri.TryCreate(backgroundImage, UriKind.RelativeOrAbsolute, out uri) || !uri.IsAbsoluteUri)
					uri = new Uri("ms-appx:///" + backgroundImage);

				element.SetValue(_backgroundProperty, new ImageBrush { ImageSource = new BitmapImage(uri) });
			}
			else
			{
				Color backgroundColor = Element.BackgroundColor;
				if (!backgroundColor.IsDefault)
				{
					element.SetValue(_backgroundProperty, backgroundColor.ToBrush());
				}
				else
				{
					object localBackground = element.ReadLocalValue(_backgroundProperty);
					if (localBackground != null && localBackground != DependencyProperty.UnsetValue)
						element.ClearValue(_backgroundProperty);
				}
			}

			_backgroundNeedsUpdate = false;
		}
	}
}