How to access to the current theme in MudBlazor component?

Viewed 1094

I've already set the current theme in my page,

<MudThemeProvider Theme="_currentTheme" />
@code
{
    private readonly MudTheme _currentTheme = new PortalTheme();
}

What is the best way to access it from another component? Should I create a cascading property?

2 Answers

To elaborate on the answer of henon, here is how I use CascadingValue.

In my MainLayout.razor, where I inject custom theme into <MudThemeProvider/>

<MudThemeProvider Theme="customTheme"/>
...
    <MudMainContent>
        <CascadingValue Value="@customTheme">
            <div class="body-container">
                @Body
            </div>
        </CascadingValue>
    </MudMainContent>
...

@code {
    MudTheme customTheme = new MudTheme()
        {
            Palette = new Palette()
            {
                Primary = new MudColor("011E41")
            }
        };
}

And then, in any other components down the hierarchy, I can use like this

<MudText Typo="Typo.h4" Style="@($"color:{Theme.Palette.Primary}")">
    Example usage of the custom theme.
</MudText>

@code {
    [CascadingParameter]
    protected MudTheme Theme { get; set; }
}

You can either use a CascadingValue or you create a singleton service which you inject into your components which holds a reference to the theme.

Related