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

#if WINDOWS_UWP

namespace Xamarin.Forms.Platform.UWP
#else

namespace Xamarin.Forms.Platform.WinRT
#endif
{
	public class MasterBackgroundConverter : Windows.UI.Xaml.Data.IValueConverter
	{
		// Obtained by comparing the Mail apps master section background to the detail background
		const double Shift = 0.03;

		public object Convert(object value, Type targetType, object parameter, string language)
		{
			SolidColorBrush brush = null;

			var element = value as FrameworkElement;
			if (element != null)
			{
				while (brush == null && element != null)
				{
					DependencyProperty property = GetBackgroundProperty(element);
					if (property != null)
					{
						value = element.GetValue(property);
						brush = value as SolidColorBrush;
						if (brush != null && brush.Color == Colors.Transparent)
							brush = null;
					}

					element = VisualTreeHelper.GetParent(element) as FrameworkElement;
				}
			}

			brush = value as SolidColorBrush;
			if (brush != null)
			{
				Windows.UI.Color wcolor = brush.Color;
				Color color = Color.FromRgba(wcolor.R, wcolor.G, wcolor.B, wcolor.A);

				double delta = Shift;
				if (color.Luminosity > .6)
					delta = -Shift;

				color = color.AddLuminosity(delta);

				return new SolidColorBrush(color.ToWindowsColor());
			}

			return null;
		}

		public object ConvertBack(object value, Type targetType, object parameter, string language)
		{
			throw new NotImplementedException();
		}

		static DependencyProperty GetBackgroundProperty(FrameworkElement element)
		{
			if (element is Control)
				return Control.BackgroundProperty;
			if (element is Panel)
				return Panel.BackgroundProperty;

			return null;
		}
	}
}