forked from AvaloniaUI/Avalonia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FluentTheme.xaml.cs
82 lines (69 loc) · 2.79 KB
/
FluentTheme.xaml.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
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Styling;
namespace Avalonia.Themes.Fluent
{
public enum DensityStyle
{
Normal,
Compact
}
/// <summary>
/// Includes the fluent theme in an application.
/// </summary>
public class FluentTheme : Styles, IResourceNode
{
private readonly ResourceDictionary _compactStyles;
private DensityStyle _densityStyle;
/// <summary>
/// Initializes a new instance of the <see cref="FluentTheme"/> class.
/// </summary>
/// <param name="sp">The parent's service provider.</param>
public FluentTheme(IServiceProvider? sp = null)
{
AvaloniaXamlLoader.Load(sp, this);
_compactStyles = (ResourceDictionary)GetAndRemove("CompactStyles");
Palettes = Resources.MergedDictionaries.OfType<ColorPaletteResourcesCollection>().FirstOrDefault()
?? throw new InvalidOperationException("FluentTheme was initialized with missing ColorPaletteResourcesCollection.");
object GetAndRemove(string key)
{
var val = Resources[key]
?? throw new KeyNotFoundException($"Key {key} was not found in the resources");
Resources.Remove(key);
return val;
}
}
public static readonly DirectProperty<FluentTheme, DensityStyle> DensityStyleProperty = AvaloniaProperty.RegisterDirect<FluentTheme, DensityStyle>(
nameof(DensityStyle), o => o.DensityStyle, (o, v) => o.DensityStyle = v);
/// <summary>
/// Gets or sets the density style of the fluent theme (normal, compact).
/// </summary>
public DensityStyle DensityStyle
{
get => _densityStyle;
set => SetAndRaise(DensityStyleProperty, ref _densityStyle, value);
}
public IDictionary<ThemeVariant, ColorPaletteResources> Palettes { get; }
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == DensityStyleProperty)
{
Owner?.NotifyHostedResourcesChanged(ResourcesChangedEventArgs.Empty);
}
}
bool IResourceNode.TryGetResource(object key, ThemeVariant? theme, out object? value)
{
// DensityStyle dictionary should be checked first
if (_densityStyle == DensityStyle.Compact
&& _compactStyles.TryGetResource(key, theme, out value))
{
return true;
}
return base.TryGetResource(key, theme, out value);
}
}
}