在 Blazor 组件之外设置 EventCallback<string>?

12 c# blazor

我正在构建一个 Blazor ProgressBar 演示,并且我试图将一些代码从我的 Blazor 组件移到一个名为 ProgressManager 的 C# 类中。这样我就可以抽象代码并使 ProgressManager 成为CascadingParameterProgressBar 组件。

我知道如何EventCallback为这样的组件设置参数:

[Parameter]
public EventCallback<string> UpdateNotification { get; set; }
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做是在 C# 类上设置这种相同类型的属性。

我的 Start 方法中有此代码:

public void ShowProgressSimulation()
{
    // Create a ProgressManager
    this.ProgressManager = new ProgressManager();
    this.ProgressManager.UpdateNotification = Refresh;
    this.ProgressManager.Start();
    
    // Refresh the UI
    StateHasChanged();
}
Run Code Online (Sandbox Code Playgroud)

不起作用的部分是: this.ProgressManager.UpdateNotification = Refresh;

错误是:

无法将方法组“Refresh”转换为非委托类型“EventCallback”。您是否打算调用该方法?

我也试过: this.ProgressManager.UpdateNotification += Refresh;

这导致“EventCallback 不能应用于方法组”(意译)。

Nie*_*ink 18

您还可以使用以下代码创建一个EventCallBack工厂,而无需新建EventCallbackFactory

Button.Clicked = EventCallback.Factory.Create( this, ClickHandler );
Run Code Online (Sandbox Code Playgroud)


Sip*_*tra 6

原来你可以从 C# 代码中分配一个事件回调,如下所示:

this.ProgressManager.UpdateNotification = new EventCallback(this, (Action)Refresh);

void Refresh() {}
Run Code Online (Sandbox Code Playgroud)

它也适用于异步方法,例如:

this.ProgressManager.UpdateNotification = new EventCallback(this, (Func<ValueTask>)RefreshAsync);

ValueTask RefreshAsync() {}
Run Code Online (Sandbox Code Playgroud)

更新

您还可以使用EventCallbackFactory更方便地创建事件回调对象,例如:

new EventCallbackFactory().Create(this, Refresh)
Run Code Online (Sandbox Code Playgroud)