Blazor将1类的值绑定到NavMenu.razor



我是Blazor的新手,希望得到您的帮助。

我用VS 2022, .Net 6启动一个新项目

创建默认项目。

步骤1:

我在项目1中添加如下Class:

namespace BlazorApp1
{
public class ClassNumber
{
public static int txtnumber = 0;
}
}

步骤2:在页面上"counter .razor";我将参数传递给Class"ClassNumber。txtnumber = currentCount;">

@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
ClassNumber.txtnumber = currentCount;
}
}

步骤3:现在我想让这个txtnumber值更新为navmenu。razor"点击

我尝试了以下操作,但没有效果("NavMenu.razor")

.........
<div class="nav-item px-3">
<NavLink class="nav-link">
<span class="oi oi-list-rich" aria-hidden="true"></span> Number change : @ClassNumber.txtnumber
</NavLink>
</div>
...........

这是我想要的图片

希望有人能帮我一个简单的例子。

对不起,我的英语不好。

谢谢。

开箱即用模板的经典问题。又快又脏;where "and Dirty"当我们扩展功能和范围时,它会回来困扰我们。

解决方案是Separation of Concerns。从组件和UI中获取数据,这就是你开始做的事情。

将数据从UI中分离。

public class CounterData
{
public int Counter { get; set; }
}

管理数据的服务:

public class CounterService
{
public CounterData Data { get; private set; } = new();
public event EventHandler? StateChanged;
public void Increment()
{
Data.Counter++;
this.StateChanged?.Invoke(null, EventArgs.Empty);
}
}

在程序中注册服务:

builder.Services.AddScoped<CounterService>();

更新Counter路由组件:

@page "/counter"
@inject CounterService Service
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @this.Service.Data.Counter</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
// No need to call StateHasChanged as the ComponentBase UI handler does it for us
private void IncrementCount()
=> this.Service.Increment();
}

和NavMenu:

@inject CounterService Service
//.....
<div class="nav-item px-3">
<NavLink class="nav-link" href="counter">
<span class="oi oi-plus" aria-hidden="true"></span> Counter @(this.Service.Data.Counter)
</NavLink>
</div>
//....
@code {
//....
protected override void OnInitialized()
{
// register a handler on the counter service StateChanged
this.Service.StateChanged += this.OnCounterChanged;
}
// This is the event handler to update the component when the counter changes
private void OnCounterChanged(object? sender, EventArgs e)
=> this.InvokeAsync(this.StateHasChanged);
public void Dispose()
{
// unhook our handler from the counter service StateChanged
// This will get called when the Renderer disposes of the component 
// when it's no longer in the RenderTree 
this.Service.StateChanged -= this.OnCounterChanged;
}
}

这是基本的Blazor通知"模式。你会经常用到它的。

相关内容

  • 没有找到相关文章

最新更新