-
Notifications
You must be signed in to change notification settings - Fork 663
/
Copy pathThemeHelper.cs
91 lines (81 loc) · 2.58 KB
/
ThemeHelper.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
88
89
90
91
using Microsoft.UI.Xaml;
using Windows.Storage;
namespace WinUIGallery.Helpers;
/// <summary>
/// Class providing functionality around switching and restoring theme settings
/// </summary>
public static class ThemeHelper
{
private const string SelectedAppThemeKey = "SelectedAppTheme";
/// <summary>
/// Gets the current actual theme of the app based on the requested theme of the
/// root element, or if that value is Default, the requested theme of the Application.
/// </summary>
public static ElementTheme ActualTheme
{
get
{
foreach (Window window in WindowHelper.ActiveWindows)
{
if (window.Content is FrameworkElement rootElement)
{
if (rootElement.RequestedTheme != ElementTheme.Default)
{
return rootElement.RequestedTheme;
}
}
}
return EnumHelper.GetEnum<ElementTheme>(App.Current.RequestedTheme.ToString());
}
}
/// <summary>
/// Gets or sets (with LocalSettings persistence) the RequestedTheme of the root element.
/// </summary>
public static ElementTheme RootTheme
{
get
{
foreach (Window window in WindowHelper.ActiveWindows)
{
if (window.Content is FrameworkElement rootElement)
{
return rootElement.RequestedTheme;
}
}
return ElementTheme.Default;
}
set
{
foreach (Window window in WindowHelper.ActiveWindows)
{
if (window.Content is FrameworkElement rootElement)
{
rootElement.RequestedTheme = value;
}
}
if (NativeHelper.IsAppPackaged)
{
ApplicationData.Current.LocalSettings.Values[SelectedAppThemeKey] = value.ToString();
}
}
}
public static void Initialize()
{
if (NativeHelper.IsAppPackaged)
{
string savedTheme = ApplicationData.Current.LocalSettings.Values[SelectedAppThemeKey]?.ToString();
if (savedTheme != null)
{
RootTheme = EnumHelper.GetEnum<ElementTheme>(savedTheme);
}
}
}
public static bool IsDarkTheme()
{
if (RootTheme == ElementTheme.Default)
{
return Application.Current.RequestedTheme == ApplicationTheme.Dark;
}
return RootTheme == ElementTheme.Dark;
}
}