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

Moh*_*van 5 themes mudblazor

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

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

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

Lam*_* Le 6

为了详细说明 henon 的答案,以下是我如何使用CascadingValue.

在 my 中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")
            }
        };
}
Run Code Online (Sandbox Code Playgroud)

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

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

@code {
    [CascadingParameter]
    protected MudTheme Theme { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


hen*_*non 2

您可以使用 CascadingValue 或创建一个范围服务,将其注入到包含对主题的引用的组件中。