[英]Blazor MainLayout as a CascadingParameter always null
[英]Calling the method in @Body from mainLayout Blazor
我找不到从 mainLayout 调用 @Body 中的方法的方法。 在主布局中:
<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://docs.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://docs.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.