If you remember, in order to make the MudThemeProvider components work properly, we use the MudBlazor component in the MainLayout.razor file. This theme supplier provides all default colors, sizes, shapes, and shadows for content elements. Also, we can use it to create a custom theme in our project.
To do that, we will modify our MainLayout.razor file:
@inherits LayoutComponentBase
@if (_isLightMode)
{
}
else
{
}
@Body
Here, we conditionally render the icons using the MudIconButton component. To select an icon, we use the icon property, and we also use the OnClick event to trigger theme switching.
Finally, we have modified the MudThemeProvider part by adding a value for the theme property.
Instead, let's add the @code part to the same file:
@code {
private bool _lightMode = true;
private MudTheme _currentTheme = new MudTheme();
private void ToggleTheme()
{
lightMode = !_lightMode ;
if(!_lightMode )
{
_currentTheme = GenerateDarkTheme();
}
else
{
_currentTheme = new MudTheme();
}
}
private MudTheme GenerateDarkTheme() =>
new MudTheme
{
Palette = new Palette()
{
Black = "#27282f",
Background = "#32343d",
BackgroundGrey = "#27282f",
Surface = "#373840",
TextPrimary = "#ffffffb2",
TextSecondary = "rgba(255,255,255, 0.50)"
}
};
}
First, we state that the default mode is the light mode and the current theme is the default theme. Then, within the ToggleTheme method, we change the present value of the _lightMode variable. If the value is incorrect, we generate a dark theme setting for the _currentTheme variable, otherwise, we set its value to the default theme. In the GeneratedDark theme method, we create a new dark theme configuration.