-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathStyleExtensions.cs
More file actions
73 lines (62 loc) · 2.62 KB
/
StyleExtensions.cs
File metadata and controls
73 lines (62 loc) · 2.62 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace CommunityToolkit.WinUI.Controls;
// Adapted from https://github.com/rudyhuyn/XamlPlus
public static partial class StyleExtensions
{
// Used to distinct normal ResourceDictionary and the one we add.
private sealed partial class StyleExtensionResourceDictionary : ResourceDictionary
{
}
public static ResourceDictionary GetResources(Style obj)
{
return (ResourceDictionary)obj.GetValue(ResourcesProperty);
}
public static void SetResources(Style obj, ResourceDictionary value)
{
obj.SetValue(ResourcesProperty, value);
}
public static readonly DependencyProperty ResourcesProperty =
DependencyProperty.RegisterAttached("Resources", typeof(ResourceDictionary), typeof(StyleExtensions), new PropertyMetadata(null, ResourcesChanged));
private static void ResourcesChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (!(sender is FrameworkElement frameworkElement))
{
return;
}
var mergedDictionaries = frameworkElement.Resources?.MergedDictionaries;
if (mergedDictionaries == null)
{
return;
}
var existingResourceDictionary =
mergedDictionaries.FirstOrDefault(c => c is StyleExtensionResourceDictionary);
if (existingResourceDictionary != null)
{
// Remove the existing resource dictionary
mergedDictionaries.Remove(existingResourceDictionary);
}
if (e.NewValue is ResourceDictionary resource)
{
var clonedResources = new StyleExtensionResourceDictionary();
clonedResources.CopyFrom(resource);
mergedDictionaries.Add(clonedResources);
}
if (frameworkElement.IsLoaded)
{
// Only force if the style was applied after the control was loaded
ForceControlToReloadThemeResources(frameworkElement);
}
}
private static void ForceControlToReloadThemeResources(FrameworkElement frameworkElement)
{
// To force the refresh of all resource references.
// Note: Doesn't work when in high-contrast.
var currentRequestedTheme = frameworkElement.RequestedTheme;
frameworkElement.RequestedTheme = currentRequestedTheme == ElementTheme.Dark
? ElementTheme.Light
: ElementTheme.Dark;
frameworkElement.RequestedTheme = currentRequestedTheme;
}
}