Search code examples
c#.netblazor.net-8.0mudblazor

Theme changing in Mudblazor


I want to have a mode change toggle in my app. I have added the toggle button in my layput page also but this does not fire any thing. How can I trigger the event?

this is my code,

@using MudBlazor
@inherits LayoutComponentBase

<MudThemeProvider @rendermode="InteractiveAuto" @bind-IsDarkMode="@(_isDarkMode)" Theme="@(_theme)"/>
<MudPopoverProvider @rendermode="InteractiveAuto" />
<MudDialogProvider @rendermode="InteractiveAuto" />
<MudSnackbarProvider @rendermode="InteractiveAuto" />

<FluentLayout>
    <FluentHeader>
           CVMain
        <FluentSpacer />
        <MudToggleIconButton Toggled="_isDarkMode"
                             ToggledChanged="ModeChanged"
                             Icon="@MudBlazor.Icons.Material.Filled.LightMode"
                             Color="@MudBlazor.Color.Info"
                             ToggledIcon="@MudBlazor.Icons.Material.Filled.DarkMode"
                             ToggledColor="@MudBlazor.Color.Dark" />
    </FluentHeader>
    <FluentStack Class="main" Orientation="Microsoft.FluentUI.AspNetCore.Components.Orientation.Horizontal" Width="100%">
        <FluentBodyContent Class="body-content">
            <div class="content">
                @Body
            </div>
        </FluentBodyContent>
    </FluentStack>
</FluentLayout>

@code {
    private bool _isDarkMode = true;
    private MudTheme _theme = new();

    private void ModeChanged(bool darkMode)
    {
        _isDarkMode = darkMode;
        StateHasChanged();
    }
}

<div id="blazor-error-ui">
    An unhandled error has occurred.
    <a href="" class="reload">Reload</a>
    <a class="dismiss">🗙</a>
</div>

I have tried with adding a custom component also but it also has the same problem. the code works perfectly in a page but as I do not want to add theme change code to every page, I need a solution with the layout.


Solution

  • I believe you have a @rendermode issue.

    Here in the Snippet you can see the bindings are working as expected.

    If all your components are InteractiveAuto then I suggest you use global @rendermode via

    App.razor

    <HeadOutlet @rendermode="@InteractiveAuto" />
    
    <Routes @rendermode="InteractiveAuto"/>