I had the same problem. I have implemented it this way.
Inside my MainLayout.razor
file I have added an onclick
event at my MudIconButton
:
<MudIconButton @onclick="ToggleDarkMode" Color="Color.Inherit" Icon="@modeIcon" />
You can see it in line 12 below.
@inherits LayoutComponentBase
<MudThemeProvider @bind-IsDarkMode="@_isDarkMode" Theme="_theme"/>
<MudDialogProvider />
<MudSnackbarProvider />
<MudLayout>
<MudAppBar Elevation="1" Color="Color.Surface">
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" OnClick="@((e) => DrawerToggle())" />
<MudText Typo="Typo.h5" Class="ml-3">Application Name Here</MudText>
<MudSpacer />
<MudIconButton @onclick="ToggleDarkMode" Color="Color.Inherit" Icon="@modeIcon" />
<MudIconButton Icon="@Icons.Material.Filled.MoreVert" Color="Color.Inherit" Edge="Edge.End" />
</MudAppBar>
<MudDrawer @bind-Open="_drawerOpen" ClipMode="DrawerClipMode.Always" Elevation="2">
<NavMenu />
</MudDrawer>
<MudMainContent>
<MudContainer MaxWidth="MaxWidth.Large" Class="my-16 pt-16">
@Body
</MudContainer>
</MudMainContent>
</MudLayout>
I have then extracted the code from the razor file to a code behind-file for MainLayout.razor
. See below:
using MudBlazor;
namespace ApplicationName.Shared
{
public partial class MainLayout
{
private MudTheme _theme = new();
private string modeIcon => _isDarkMode ? Icons.Outlined.DarkMode : @Icons.Outlined.LightMode;
private bool _isDarkMode;
bool _drawerOpen = true;
void ToggleDarkMode()
{
_isDarkMode = !_isDarkMode;
}
void DrawerToggle()
{
_drawerOpen = !_drawerOpen;
}
}
}
Here I am changing the icon depending on the dark mode setting from the client and then updating the bool in the method ToggleDarkMode()
. Remember to update the namespace.
At runtime, this is what happens:
Live demo of MudBlazor Dark Mode
Hope this works for you and everyone else who has the same problem :)
OnClick
parameter - perhaps you should use that instead of@onclick
? – Neurath