簡體   English   中英

從 mainLayout Blazor 調用 @Body 中的方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM