Search code examples
c#mudblazor

How to navigate through MudTabPanels when clicking a button?


When the user clicks on a button, it must go to a specific tab of my MudTabPanel, is that possible?

<MudTabs Elevation="0" Rounded="true" Centered="true">
    <MudTabPanel Text="Tab1" ID="1" tabindex="1" @bind-ActivePanelIndex="activeIndex">
    </MudTabPanel>
    <MudTabPanel Text="Tab2" ID="2" tabindex="2" @bind-ActivePanelIndex="activeIndex">
    </MudTabPanel>
    <MudTabPanel Text="Tab3" ID="3" tabindex="3" @bind-ActivePanelIndex="activeIndex">
    </MudTabPanel>
</MudTabs>
<MudButton OnClick="@(()=>GoToTab())">Go To Tab 3</MudButton>

@code {
    public int activeIndex { get; set; } = 1;

    public async Task GoToTab()
    {
        activeIndex = 3;
        StateHasChanged();
    }
}

Solution

  • You can manipulate the ActivePanelIndex property for MudTabs docs

    Note The index starts starts at 0

    <MudTabs Elevation="0" Rounded="true" Centered="true" @bind-ActivePanelIndex="@_activePanel">
        <MudTabPanel Text="Tab1" ID="1" tabindex="1" >
        </MudTabPanel>
        <MudTabPanel Text="Tab2" ID="2" tabindex="2" >
        </MudTabPanel>
        <MudTabPanel Text="Tab3" ID="3" tabindex="3" >
        </MudTabPanel>
    </MudTabs>
    
    <MudButton OnClick="@(()=>GoToTab(2))">Go To Tab 3</MudButton>
    
    
    @code{
        int _activePanel;
        void GoToTab(int tabIndex){
            _activePanel = tabIndex;
        }
    }
    

    MudBlazor snippet