Skip to content

Instantly share code, notes, and snippets.

@J-Swift
Created October 23, 2022 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save J-Swift/b21a96cae47d8ea7db48081d5daf57ca to your computer and use it in GitHub Desktop.
Save J-Swift/b21a96cae47d8ea7db48081d5daf57ca to your computer and use it in GitHub Desktop.
Basic example of programmatic ResourceDictionary configuration
public class App : Application
{
public App()
{
StyleUtils.ConfigureResources(Resources, new ThemeLight());
...
}
}
public static class StyleUtils
{
public static readonly Thickness PagePadding = 16;
public class ThemeLight : ITheme
{
// Material theming
public Color ColorPrimary { get; } = Color.FromArgb("#FF0D4EB6");
public Color ColorBackground { get; } = Color.FromArgb("#FFFFFFFF");
public Color ColorSurface { get; } = Color.FromArgb("#FFFFFFFF");
public Color ColorOnPrimary { get; } = Color.FromArgb("#FFFFFFFF");
public Color ColorOnBackground { get; } = Color.FromArgb("#FF222426");
public Color ColorOnSurface { get; } = Color.FromArgb("#FF222426");
// Typography
public Color ColorPlaceholder { get; }
public ThemeLight()
{
ColorPlaceholder = ColorOnBackground.WithAlpha(0.5f);
}
}
public static void ConfigureResources(ResourceDictionary r, ITheme theme)
{
SetTheme(r, theme);
r.Add(new Style(typeof(NavigationPage))
{
Setters =
{
ThemeUtils.GetSetterDynamic(NavigationPage.BarBackgroundColorProperty, nameof(ITheme.ColorPrimary)),
ThemeUtils.GetSetterDynamic(NavigationPage.BarTextColorProperty, nameof(ITheme.ColorOnPrimary)),
}
});
r.Add(new Style(typeof(Page))
{
Setters =
{
ThemeUtils.GetSetterDynamic(Page.BackgroundColorProperty, nameof(ITheme.ColorBackground)),
}
});
}
public static void SetTheme(ResourceDictionary r, ITheme theme)
{
// TODO(jpr): Page.BackgroundColor is not respecting dynmamic resource changes...
// see: https://github.com/dotnet/maui/issues/4516
Theme.Current = theme;
r[nameof(ITheme.ColorPrimary)] = theme.ColorPrimary;
r[nameof(ITheme.ColorBackground)] = theme.ColorBackground;
r[nameof(ITheme.ColorSurface)] = theme.ColorSurface;
r[nameof(ITheme.ColorOnPrimary)] = theme.ColorOnPrimary;
r[nameof(ITheme.ColorOnBackground)] = theme.ColorOnBackground;
r[nameof(ITheme.ColorOnSurface)] = theme.ColorOnSurface;
r[nameof(ITheme.ColorPlaceholder)] = theme.ColorPlaceholder;
}
public static class ThemeUtils
{
public static Setter GetSetterDirect(BindableProperty property, object value) => new() { Property = property, Value = value };
public static Setter GetSetterDynamic(BindableProperty property, string key) => new() { Property = property, Value = new Microsoft.Maui.Controls.Internals.DynamicResource(key) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment