我找不到从mainLayout调用@Body中方法的方法。在mainLayout:中
<div class="page"> <div class="sidebar">
<NavMenu />
</div>
<div class="main">
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<div class="top-row px-4">
<a href="https://learn.microsoft.com/en-us/aspnet/" target="_blank">About</a>
</div>
<div class="content px-4">
@Body
</div>
</div>
在Main Layout中有一个Click me按钮,按下该按钮需要调用Body中的方法。从mainLayout调用Body中的方法有哪些选项?
以下是应用于代码的Blazor通知模式。
定义服务。
public class NotifyStateService
{
public event EventHandler? EventClick;
public void NotifyEventClick(object sender)
{
if (this.EventClick != null)
this.EventClick(sender, EventArgs.Empty);
}
}
并将其注册为
//Program
builder.Services.AddScoped<NotifyStateService>();
主布局
@inherits LayoutComponentBase
<PageTitle>Server</PageTitle>
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<div class="top-row px-4">
<a href="https://learn.microsoft.com/aspnet/" target="_blank">About</a>
</div>
<article class="content px-4">
@Body
</article>
</main>
</div>
<NotificationPanel />
@code {
[Inject] private NotifyStateService? service {get; set;}
// second null forgiving declaration as compiler too dumb to know service can't be null in this context
private NotifyStateService Service => service!;
private void IncrementCount()
=> this.Service.NotifyEventClick(this);
}
演示页面
@page "/Increment"
@implements IDisposable
<h3>Incrementor</h3>
<div class=m-2 p-2>
Counter: @this.counter
</div>
@code {
[Inject] private NotifyStateService? service { get; set; }
private NotifyStateService Service => service!;
private int counter = 0;
protected override void OnInitialized()
{
this.Service.EventClick += this.Increment;
base.OnInitialized();
}
private void Increment(object? sender, EventArgs e)
{
counter++;
this.InvokeAsync(StateHasChanged);
}
public void Dispose()
=> this.Service.EventClick -= this.Increment;
}