Proposal: Theme Keys
Author: MrJulCreated Sep 17, 2026Updated Sep 17, 2026
Themes usually consist of hundreds of string resource keys. Having a comprehensive list of these keys and their matching type isn't easy.
Instead, we could maintain a list as standard properties, and type those keys.
// ThemeKey: reference equality only! The name is only here for easier debugging.
public sealed class ThemeKey<T>(string name)
{
public string Name { get; } = name;
public override string ToString() => Name;
}
// In Avalonia.Themes.Fluent
public static class ButtonThemeKeys
{
public static ThemeKey<Brush> Background { get; } = new(nameof(Background));
}In XAML theme files:
<!-- Definition -->
<SolidColorBrush x:Key="{x:Static ButtonThemeKeys.Background}" Color="Red" />
<!-- Usage in Button.axaml -->
<Setter Property="Background" Value="{DynamicResource {x:Static ButtonThemeKeys.Background}}" />Pros:
- No more arbitrary strings: a nice compilation error in case of a typo, for both theme authors and users.
- Part of the public theme API.
- Resource hierarchy instead of a flat list (classes can be split or nested as needed).
- Easy to see if a resource is missing in unit tests.
- A key can be made obsolete in the future if needed.
About the ThemeKey<T> class:
T allows unit tests to verify the resource's type, and doubles as a documented type for users. We could even make the XAML compiler verify the type if we want to.
Alternatives include enums or plain object keys, but we'd lose the advantages of having T.
Source: AvaloniaUI/Avalonia