Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 42 ยท Styling and Resources

Resources and Styles

Centralize colors, fonts and control styles in .NET MAUI with ResourceDictionary, implicit and explicit styles, StaticResource vs DynamicResource, BasedOn, style classes and merged dictionaries.

If you set TextColor="#512BD4" on forty labels and then your designer asks for a different purple, you have forty edits and a few you will miss. MAUI solves this with resources: named values (colors, numbers, fonts, whole styles) that you define once and reference everywhere. This lesson covers resource dictionaries, the different kinds of styles, and how lookup works, so you can restyle an entire app by changing one file.

The XAML in this lesson is the real MAUI syntax, shown read-only. The runnable block is a plain C# stand-in that models how resource lookup and style inheritance work.

Defining resources

Resources live in a ResourceDictionary. You can attach one to any element, a page, or the whole application (App.xaml):

XML
<ContentPage.Resources>
    <Color x:Key="Brand">#512BD4</Color>
    <x:Double x:Key="BaseSpacing">12</x:Double>
    <x:String x:Key="AppTitle">Recipe Box</x:String>
    <Thickness x:Key="PagePadding">16,12</Thickness>
</ContentPage.Resources>

Reference them with StaticResource or DynamicResource:

XML
<Label Text="{StaticResource AppTitle}"
       TextColor="{StaticResource Brand}"
       Margin="{StaticResource PagePadding}" />

The default template splits resources into two files, Resources/Styles/Colors.xaml and Resources/Styles/Styles.xaml, merged by App.xaml:

XML
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
            <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

How lookup works

When you write {StaticResource Brand}, MAUI searches outward: the element's own Resources, then its parent, up to the page, and finally Application.Resources. The first match wins. That gives you overrides for free: define Brand on one page and only that page changes.

flowchart TD
    A["Label.Resources"] --> B["StackLayout.Resources"]
    B --> C["ContentPage.Resources"]
    C --> D["Application.Resources<br/>(including merged dictionaries)"]
    D --> E["Not found: XamlParseException"]

Lookup moves from the closest element outward; the first match wins.

StaticResource vs DynamicResource

StaticResource DynamicResource
Resolved Once, when the XAML loads Every time the resource changes
Speed Faster Slightly slower
Must exist before use Yes (defined earlier or in an outer scope) No
Use for Fixed values Values that change at runtime, such as theme colors
C#
Application.Current!.Resources["Brand"] = Colors.DeepPink;   // only DynamicResource users update

A StaticResource for a missing key throws at load time, which is useful because you find typos immediately.

Styles: implicit, explicit and classes

A Style is a named bundle of property setters:

XML
<Style x:Key="TitleLabel" TargetType="Label">
    <Setter Property="FontSize" Value="28" />
    <Setter Property="FontAttributes" Value="Bold" />
    <Setter Property="TextColor" Value="{StaticResource Brand}" />
</Style>

Explicit style: has an x:Key, applied by name: <Label Style="{StaticResource TitleLabel}" />.

Implicit style: has no key, so it applies to every element of that type in scope:

XML
<Style TargetType="Button">
    <Setter Property="BackgroundColor" Value="{StaticResource Brand}" />
    <Setter Property="CornerRadius" Value="8" />
</Style>

Implicit styles match the exact type only. A style for Label does not apply to a Span, and it does not apply to a subclass.

Style classes: a style with Class="..." is applied by name, and an element can have several:

XML
<Style TargetType="Label" Class="Muted">
    <Setter Property="TextColor" Value="Gray" />
</Style>

<Label Text="Updated yesterday" StyleClass="Muted, Small" />

Classes compose better than explicit styles. Use them for small reusable traits such as Muted, Danger or Card.

Inheritance with BasedOn

XML
<Style x:Key="HeadingLabel" TargetType="Label" BasedOn="{StaticResource TitleLabel}">
    <Setter Property="FontSize" Value="20" />
</Style>

BasedOn copies the parent's setters, and the child overrides what it sets. A neat trick is the implicit style based on the base control style:

XML
<Style TargetType="Label" BasedOn="{StaticResource DefaultLabel}" />

(The default template's implicit styles for Label, Button and others are written this way.)

Precedence: who wins?

When the same property is set in several ways, the most local wins: a local value on the element beats a style, and a style beats the control's default. A property set by a VisualState or a Trigger overrides the style while it is active (next lessons). Because of this, avoid setting TextColor locally on controls that you expect to respond to the theme.

Fonts and images as resources

Fonts are registered in MauiProgram.cs and referenced by their alias:

C#
builder.ConfigureFonts(fonts =>
{
    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
XML
<Label FontFamily="OpenSansSemibold" Text="Hello" />

Put images in Resources/Images (SVG files are converted to the right PNG sizes at build time). Use lowercase file names with no spaces and refer to them without the extension for SVG: Source="logo.svg" or logo.png.

Try it: a resource dictionary with scope and styles

This stand-in implements the two ideas that matter: scoped lookup and BasedOn inheritance.

C# Stand-in: resource lookup and BasedOn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The page-level Brand wins over the application one, and the HeadingLabel style inherits Bold and TextColor from TitleLabel while overriding FontSize. The TextColor resolves to the page's pink because the lookup starts at the element.

Practical advice

  • Name resources by purpose (Primary, Danger, SurfaceBackground) rather than appearance (Purple). A rename from purple to blue then does not make the code lie.
  • Keep colors in Colors.xaml, styles in Styles.xaml, and one more file per big feature if you like. Merge them all in App.xaml.
  • Prefer implicit styles for app-wide defaults, classes for variations, and explicit styles sparingly.
  • Style ContentPage once (BackgroundColor) instead of on every page.
  • Use DynamicResource only for values that really change at runtime, as in the themes lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does StaticResource look first for a key?

    Lookup starts at the closest element and moves outward, so closer definitions override outer ones.
  2. 2. What does a Style without x:Key do?

    An implicit style applies automatically to elements of exactly that type within its scope.
  3. 3. Which resource reference updates automatically when the resource value changes at runtime?

    DynamicResource subscribes to changes; StaticResource reads the value once at load time.
  4. 4. A Label has TextColor set locally and also a style that sets TextColor. Which wins?

    A value set directly on the element has higher precedence than the same property in a style.

Summary

  • Resources are named values and styles in ResourceDictionary objects, merged at app level.
  • Lookup goes from the element outward; the closest definition wins.
  • Use DynamicResource for values that change at runtime and StaticResource otherwise.
  • Styles can be implicit, explicit or classes, and can inherit with BasedOn.

Next: Themes and Dark Mode