最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Use ref of inherited component in .NET Blazor - Stack Overflow

programmeradmin3浏览0评论

How can I access the MudMenu ref properties when using the Menu component? If I use the Menu _menuRef, then I don't have access to MudMenu properties. If I use MudMenu _menuRef, then I get access to the properties but instead get an error saying it can't convert MudMenu to Menu.

Are there any workarounds for this? Can I set Menu.razor to always be of type MudMenu? Or can I expose the properties manually somehow?

Menu.razor:

@inherits MudMenu

@{
    base.BuildRenderTree(__builder);
}

@code {

    protected override void OnInitialized()
    {
        base.OnInitialized();
        PopoverClass = "mt-1";
        Dense = true;
    }

}

Using component:

<Menu @ref="@_menuRef">

@code {
    MudMenu _menuRef;

    async Task Test()
    {
        await _menuRef.CloseMenuAsync();
    }
}

How can I access the MudMenu ref properties when using the Menu component? If I use the Menu _menuRef, then I don't have access to MudMenu properties. If I use MudMenu _menuRef, then I get access to the properties but instead get an error saying it can't convert MudMenu to Menu.

Are there any workarounds for this? Can I set Menu.razor to always be of type MudMenu? Or can I expose the properties manually somehow?

Menu.razor:

@inherits MudMenu

@{
    base.BuildRenderTree(__builder);
}

@code {

    protected override void OnInitialized()
    {
        base.OnInitialized();
        PopoverClass = "mt-1";
        Dense = true;
    }

}

Using component:

<Menu @ref="@_menuRef">

@code {
    MudMenu _menuRef;

    async Task Test()
    {
        await _menuRef.CloseMenuAsync();
    }
}
Share Improve this question edited Apr 2 at 1:50 Zhi Lv 22k1 gold badge27 silver badges37 bronze badges asked Mar 30 at 21:08 bobbob 1282 silver badges12 bronze badges 1
  • Please show us MudMenu – mjwills Commented Mar 30 at 23:11
Add a comment  | 

1 Answer 1

Reset to default 1

The simplest and most maintainable approach is Option 1: Expose MudMenu Methods in Menu. It keeps your custom Menu component as the single point of truth, avoids type mismatches, and aligns with Blazor’s component design philosophy. Here’s the full implementation again for clarity:

Menu.razor:

@inherits MudMenu

@{
    base.BuildRenderTree(__builder);
}

@code {
    protected override void OnInitialized()
    {
        base.OnInitialized();
        PopoverClass = "mt-1";
        Dense = true;
    }

    public async Task CloseMenuAsync()
    {
        await base.CloseMenuAsync();
    }
}

Using Component:

<Menu @ref="@_menuRef">
    <!-- Menu content -->
</Menu>

@code {
    Menu _menuRef;

    async Task Test()
    {
        await _menuRef.CloseMenuAsync();
    }
}

This way, you can continue to use Menu as your custom component while accessing MudMenu functionality without type errors.

发布评论

评论列表(0)

  1. 暂无评论