Dark/light Theme Blazor
Asked Answered
S

6

8

i have tied so many ways for switching Between Dark and Light Mode in Blazor.with different packages and Even Manually with css. but they never workedout For Me.can someone Give me complete guid on how can i do this?Thank

here is the latest thing i have tried with MudBlazor:

<MudThemeProvider Theme="new MudTheme()" @bind-IsDarkMode="@_isDarkMode"/>
<MudIconButton @onclick="ToggleDark" Icon="@modeIcon"/>

@code {
bool _isDarkMode = false;
private string modeIcon => _isDarkMode? Icons.Filled.DarkMode : Icons.Filled.LightMode;
private void ToggleDark() => _isDarkMode = !_isDarkMode;
}
Sidell answered 2/2, 2022 at 6:4 Comment(1)
I'm not too familiar with MudBlazor, but the documentation says the IconButton has an OnClick parameter - perhaps you should use that instead of @onclick?Neurath
S
7

so basically, this might be late, but i will post it for if someone was looking for it mudblazor docs been updated

link can be found here

<MudThemeProvider @ref="@_mudThemeProvider" @bind-IsDarkMode="@_isDarkMode"/>

@code {
    private bool _isDarkMode;
    private MudThemeProvider _mudThemeProvider;
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _isDarkMode = await _mudThemeProvider.GetSystemPreference();
            StateHasChanged();
        }
    }
}

basically this worked for auto theme, which is fine by me for now

Sweetsop answered 4/9, 2022 at 2:39 Comment(0)
D
4

Here's an example:

https://try.mudblazor.com/snippet/QammkMHEJKzZundd

<MudThemeProvider @bind-IsDarkMode="@isDarkMode"/>
<MudSwitch
    @bind-Checked="@isDarkMode"
    Color="Color.Primary"
    Label="Toggle Light/Dark Mode"/>

@code{
    private bool isDarkMode;
}

Source:

This example is a simplified version of an example from the official MudBlazor documentation. Here's a link: https://mudblazor.com/customization/overview#dark-palette

Disembody answered 2/2, 2022 at 21:25 Comment(3)
I already tried it. It doesn't workSidell
In that case, you may need to provide more info since this is a code example from the official MudBlazor documentation. Feel free to have a look at the installation guide of MudBlazor just in case: mudblazor.com/getting-started/…Disembody
Theme="_theme" - remove this and will work just fine on default theme.Stint
E
3

I struggled with this as well. The MudBlazor docs neglect to inform you that you must call StateHasChanged() from the layout component (MainLayout) after toggling IsDarkMode. I discovered this after researching how their documentation website works. Look at (https://github.com/MudBlazor/MudBlazor/blob/d05b8d0ef3480c69a7db754d0d8ce9abdbd544ad/src/MudBlazor.Docs/Shared/MainLayout.razor.cs)

The operative code is (edited):

public partial class MainLayout : LayoutComponentBase, IDisposable
{ 
   [Inject] private  LayoutService LayoutService { get; set; }
   
   private MudThemeProvider _mudThemeProvider;

   protected override void OnInitialized()
   {
       LayoutService.MajorUpdateOccured += LayoutServiceOnMajorUpdateOccured;
       base.OnInitialized();
   }

   public void Dispose()
   {
       LayoutService.MajorUpdateOccured -= LayoutServiceOnMajorUpdateOccured;
   }

   private void LayoutServiceOnMajorUpdateOccured(object sender, EventArgs e) => StateHasChanged();
}

Note that MainLayout subscribes to the MajorUpdateOccured event and calls StateHasChanged when the event is invoked.

If you look at LayoutService (https://github.com/MudBlazor/MudBlazor/blob/d05b8d0ef3480c69a7db754d0d8ce9abdbd544ad/src/MudBlazor.Docs/Services/LayoutService.cs), you will see how ToggleDarkMode works

public event EventHandler MajorUpdateOccured;

private void OnMajorUpdateOccured() => MajorUpdateOccured?.Invoke(this,EventArgs.Empty);

public async Task ToggleDarkMode()
{
   IsDarkMode = !IsDarkMode;
   _userPreferences.DarkTheme = IsDarkMode;
   await _userPreferencesService.SaveUserPreferences(_userPreferences);
   OnMajorUpdateOccured();
}

In summary, you have to call StateHasChanged from the layout so that the entire site is re-rendered. So you have to provide a way to propagate the dark mode change from your settings screen to your layout component.

Eyecatching answered 12/5, 2022 at 2:55 Comment(1)
its funny they are not using blazor.Sweetsop
E
0

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 :)

Extravagance answered 12/8, 2022 at 8:40 Comment(0)
H
0

Thought this might help some people, if you just want a dark theme without toggling on and off with a button you don't have to use OnAfterRenderAsync and StateHasChanged functions. Just define _isDarkMode and set true and bind to it as below. Bit nicer since you don't have to reload the page and get that brief flashing when your site loads to switch themes.

<MudThemeProvider @ref="@_mudThemeProvider" @bind-IsDarkMode="@_isDarkMode" />

<MudText Typo="Typo.h5" Class="ml-3">Dark Theme</MudText>

@code {

    private MudThemeProvider _mudThemeProvider;
    private bool _isDarkMode = true;
}

Link here

Holm answered 10/6 at 16:12 Comment(0)
M
-4

you should give a condition in class. so in your claas:



<div class="light ? class : class2"></div>


export defaut{
data(){
return {
light : true;
}
}

Mercia answered 2/2, 2022 at 6:15 Comment(1)
This is not relevant to Blazor - the question is about using the MudBlazor components in a Blazor project.Neurath

© 2022 - 2024 — McMap. All rights reserved.