简体   繁体   English

从 mainLayout Blazor 调用 @Body 中的方法

[英]Calling the method in @Body from mainLayout Blazor

I can't find a way to call the method in @Body from mainLayout.我找不到从 mainLayout 调用 @Body 中的方法的方法。 in 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://docs.microsoft.com/en-us/aspnet/" target="_blank">About</a>
    </div>

    <div class="content px-4">
        @Body
    </div>
</div>

In the Main Layout there is a Click me button, by pressing which you need to call the method that is in the Body.在 Main Layout 中有一个 Click me 按钮,通过按下您需要调用 Body 中的方法。 What are the options for calling the method in Body from mainLayout?从 mainLayout 调用 Body 中的方法有哪些选项?

Here's the Blazor Notification pattern applied to your code.这是应用于您的代码的 Blazor 通知模式。

Define a service.定义服务。

public class NotifyStateService
{
    public event EventHandler? EventClick;

    public void NotifyEventClick(object sender)
    {
        if (this.EventClick != null)
            this.EventClick(sender, EventArgs.Empty);
    }
}

and register it并注册

//Program

builder.Services.AddScoped<NotifyStateService>();

MainLayout主布局

@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);
}

Demo page演示页面

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM