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

#if WINDOWS_UWP

namespace Xamarin.Forms.Platform.UWP
#else

namespace Xamarin.Forms.Platform.WinRT
#endif
{
	public class ActivityIndicatorRenderer : ViewRenderer<ActivityIndicator, Windows.UI.Xaml.Controls.ProgressBar>
	{
#if !WINDOWS_UWP
		Windows.UI.Xaml.Media.SolidColorBrush _resourceBrush;
#endif
		object _foregroundDefault;

		protected override void OnElementChanged(ElementChangedEventArgs<ActivityIndicator> e)
		{
			base.OnElementChanged(e);

			if (e.NewElement != null)
			{
				if (Control == null)
				{
					SetNativeControl(new Windows.UI.Xaml.Controls.ProgressBar { IsIndeterminate = true });

					Control.Loaded += OnControlLoaded;
				}

				// UpdateColor() called when loaded to ensure we can cache dynamic default colors
				UpdateIsRunning();
			}
		}

		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			base.OnElementPropertyChanged(sender, e);

			if (e.PropertyName == ActivityIndicator.IsRunningProperty.PropertyName)
				UpdateIsRunning();
			else if (e.PropertyName == ActivityIndicator.ColorProperty.PropertyName)
				UpdateColor();
		}

		void OnControlLoaded(object sender, RoutedEventArgs routedEventArgs)
		{
#if !WINDOWS_UWP
			_resourceBrush = (Control.Resources["ProgressBarIndeterminateForegroundThemeBrush"] as Windows.UI.Xaml.Media.SolidColorBrush);
			_foregroundDefault = _resourceBrush.Color;
#else
			_foregroundDefault = Control.GetForegroundCache();
#endif
			UpdateColor();
		}

		void UpdateColor()
		{
			Color color = Element.Color;

			if (color.IsDefault)
			{
#if !WINDOWS_UWP
				_resourceBrush.Color = (Windows.UI.Color) _foregroundDefault;
#else
				Control.RestoreForegroundCache(_foregroundDefault);
#endif
			}
			else
			{
#if !WINDOWS_UWP
				_resourceBrush.Color = color.ToWindowsColor();
#else
				Control.Foreground = color.ToBrush();
#endif
			}
		}

		void UpdateIsRunning()
		{
			Opacity = Element.IsRunning ? 1 : 0;
		}
	}
}