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

blazor - Close sidebar automatically when user clicks NavLink - Stack Overflow

programmeradmin3浏览0评论

In my Blazor WASM Standalone project, I have a collapsible sidebar used for navigation. I currently keep the state of the sidebar in my centralized state container i.e. isSidebarExpanded = true or false.

I want to make sure whenever a user navigates to a new page by clicking a link i.e. NavLink, I want to automatically close the sidebar.

One idea is to capture the NavLink click event and update the isSidebarExpanded to false.

Alternatively, I can make sure the isSidebarExpanded is set to false in OnInitialized() event in every page but this requires repetitive code.

I'm not sure if these approaches are overly complicating this scenario. I was wondering how others have handled this case.

In my Blazor WASM Standalone project, I have a collapsible sidebar used for navigation. I currently keep the state of the sidebar in my centralized state container i.e. isSidebarExpanded = true or false.

I want to make sure whenever a user navigates to a new page by clicking a link i.e. NavLink, I want to automatically close the sidebar.

One idea is to capture the NavLink click event and update the isSidebarExpanded to false.

Alternatively, I can make sure the isSidebarExpanded is set to false in OnInitialized() event in every page but this requires repetitive code.

I'm not sure if these approaches are overly complicating this scenario. I was wondering how others have handled this case.

Share Improve this question edited Mar 17 at 2:59 Sam asked Mar 17 at 2:33 SamSam 30.6k76 gold badges252 silver badges465 bronze badges 1
  • Chrck out the NavigationManager LocationChanged event. – abbottmw Commented Mar 17 at 3:07
Add a comment  | 

1 Answer 1

Reset to default 2

Inject the NavigationManager and register for the LocationChanged event in your sidebar component. Here's the basic code template:

@implement IDisposable
@inject NavigationManager NavigationManager

//...
    protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += OnLocationChanged;
    }

    public void Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
    }

    private void OnLocationChanged(object? sender, LocationChangedEventArgs args)
    {
        //Update State
        StateHasChanged();
    }
发布评论

评论列表(0)

  1. 暂无评论