This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
BackgroundManager.cs
87 lines (72 loc) · 2.47 KB
/
BackgroundManager.cs
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
using System;
using System.ComponentModel;
using Xamarin.Forms.Internals;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
internal static class BackgroundManager
{
public static void Init(IVisualElementRenderer renderer)
{
_ = renderer ?? throw new ArgumentNullException($"{nameof(BackgroundManager)}.{nameof(Init)} {nameof(renderer)} cannot be null");
renderer.ElementPropertyChanged += OnElementPropertyChanged;
renderer.ElementChanged += OnElementChanged;
}
public static void Dispose(IVisualElementRenderer renderer)
{
_ = renderer ?? throw new ArgumentNullException($"{nameof(BackgroundManager)}.{nameof(Init)} {nameof(renderer)} cannot be null");
renderer.ElementPropertyChanged -= OnElementPropertyChanged;
renderer.ElementChanged -= OnElementChanged;
if (renderer.Element != null)
{
renderer.Element.PropertyChanged -= OnElementPropertyChanged;
}
}
static void UpdateBackgroundColor(AView Control, VisualElement Element, Color? color = null)
{
if (Element == null || Control == null)
return;
var finalColor = color ?? Element.BackgroundColor;
if (finalColor.IsDefault)
Control.SetBackground(null);
else
Control.SetBackgroundColor(finalColor.ToAndroid());
}
static void UpdateBackground(AView Control, VisualElement Element)
{
if (Element == null || Control == null)
return;
Brush background = Element.Background;
Control.UpdateBackground(background);
}
static void OnElementChanged(object sender, VisualElementChangedEventArgs e)
{
Performance.Start(out string reference);
if (e.OldElement != null)
{
e.OldElement.PropertyChanged -= OnElementPropertyChanged;
}
if (e.NewElement != null)
{
var renderer = sender as IVisualElementRenderer;
e.NewElement.PropertyChanged += OnElementPropertyChanged;
UpdateBackgroundColor(renderer?.View, renderer?.Element);
UpdateBackground(renderer?.View, renderer?.Element);
}
Performance.Stop(reference);
}
static void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
{
var renderer = (sender as IVisualElementRenderer);
UpdateBackgroundColor(renderer?.View, renderer?.Element);
}
else if (e.PropertyName == VisualElement.BackgroundProperty.PropertyName)
{
var renderer = (sender as IVisualElementRenderer);
UpdateBackground(renderer?.View, renderer?.Element);
}
}
}
}