How to access to the current theme in MudBlazor component?
Asked Answered
S

2

5

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?

Subtotal answered 31/10, 2021 at 20:30 Comment(0)
C
2

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

Constraint answered 22/11, 2021 at 15:36 Comment(1)
A singleton is not recommended as a singleton is a singleton for ALL instances of the app on the website. So if you changed the Theme for one user, it would change it for every user on the site even though they are on different browsers thousands of miles apart. Recommended is the use of a Cascading Parameter, or Injecting it as Scoped.Triplane
D
6

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; }
}
Davisson answered 14/4, 2022 at 8:47 Comment(0)
C
2

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

Constraint answered 22/11, 2021 at 15:36 Comment(1)
A singleton is not recommended as a singleton is a singleton for ALL instances of the app on the website. So if you changed the Theme for one user, it would change it for every user on the site even though they are on different browsers thousands of miles apart. Recommended is the use of a Cascading Parameter, or Injecting it as Scoped.Triplane

© 2022 - 2024 — McMap. All rights reserved.