Set site wide style or theme for Blazor with fluent-ui

1.3k Views Asked by At

We're working with Blazor and Fluent UI makes sense to adopt as both are Microsoft.

However, I cannot find documentation on how to apply a theme (a colour palette at least) to the existing Blazor Fluent UI components. I mean site wide.

Some styles such as for the FluentHeader can be overridden in a site wide stylesheet (app.css). And for the css vars applied on those it is sufficient to assign them in app.css. But most components (e.g. FluentButton) use shadow root. The above doesn't work there. Neither is it possible to change css rules that aren't a design token, such as making font weight bold.

I have found the list of design tokens
https://microsoft.github.io/fluentui-design-tokens/

General documentation on design tokens
https://learn.microsoft.com/en-us/fluent-ui/web-components/design-system/design-tokens

And specific documentation on design tokens for Blazor
https://www.fluentui-blazor.net/DesignTokens

But none of these tell me how to actually apply a palette site wide. There's instructions on how to apply design tokens to specific components, and there's the themeprovider but that's both suggested as a fall-back option only and uses a subset of design tokens.

I feel like I'm overlooking something obvious but I've asked other to help out and so far nobody could find it.

2

There are 2 best solutions below

1
On

You can use FluentThemeProvider like this:

Include FluentThemeProvider in App.razor:

<FluentThemeProvider Theme="@coloured">    
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</FluentThemeProvider>

Define Theme:

using Microsoft.FluentUI.Theme;

public class MyTheme : ITheme
{
    public IFontStyles FontStyles { get; set; } = new FluentFontStyles();
    public IColorPalette Palette { get; set; } = new MyColorPalette();
}

public class MyColorPalette : IColorPalette
{
    public string ThemePrimary { get; set; } = "#00FF00"; // set primary color
}

Components within your application can now access the theme defined in the FluentThemeProvider.

<FluentButton Primary="true">Click me</FluentButton>
1
On

You should use FluentDesignTheme as described in the docs for FluentUI Blazor: https://www.fluentui-blazor.net/DesignTheme