这是我的代码:
RiskForm.razor
@page "/riskform"
RiskForm
<MudTabs Elevation="4" Rounded="true" Centered="true" Color="@Color.Secondary">
<MudTabPanel Text="tab1">
<Counter />
</MudTabPanel>
<MudTabPanel Text="tab2" />
<MudTabPanel Text="tab3" />
<MudTabPanel Text="tab4" />
<MudTabPanel Text="tab5" />
<MudTabPanel Text="tab6" />
<MudTabPanel Text="tab7" />
</MudTabs>
Counter.razor是默认值。
@page "/counter"
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<MudTextField @bind-Value="currentCount" Label="current count" Variant="Variant.Outlined" />
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
当我递增表1中的计数器并进入下一个表时,当我返回表1时,我会丢失计数器计数。它再次从0初始化。
如何在浏览选项卡时保持计数器递增的状态?
要保持状态,可以执行以下操作:
public class PersistentState
{
private int _currentCount;
public int CurrentCounter
{
get { return _currentCount; }
set
{
_currentCount = value;
NotifyStateChanged();
}
}
public event Action? OnChange;
private void NotifyStateChanged() => OnChange?.Invoke();
}
在Program.cs(.NET6(中,将服务添加到容器
builder.Services.AddScoped<PersistentState>();
最后在Counter.razor 中注入PersistentState
@page "/counter"
@inject PersistentState state
<h1>Counter</h1>
<p>Current count: @state.CurrentCounter</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
//private int currentCount = 0;
private void IncrementCount()
{
//currentCount++;
state.CurrentCounter++;
}
}