如何访问 MudBlazor 组件中的当前主题?

How to access to the current theme in MudBlazor component?

我已经在我的页面中设置了当前主题,

<MudThemeProvider Theme="_currentTheme" />
@code
{
    private readonly MudTheme _currentTheme = new PortalTheme();
}

从另一个组件访问它的最佳方式是什么?我应该创建级联 属性 吗?

您可以使用 CascadingValue 或创建单例服务,将其注入包含对主题的引用的组件中。

为了详细说明henon的答案,这里是我如何使用CascadingValue

在我的 MainLayout.razor 中,我将自定义主题注入 <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")
            }
        };
}

然后,在层次结构中的任何其他组件中,我可以像这样使用

<MudText Typo="Typo.h4" Style="@($"color:{Theme.Palette.Primary}")">
    Example usage of the custom theme.
</MudText>

@code {
    [CascadingParameter]
    protected MudTheme Theme { get; set; }
}