简体   繁体   English

设置事件回调<string>在 Blazor 组件之外?

[英]Set EventCallback<string> outside of a Blazor component?

I am building a Blazor ProgressBar demo, and I am attempting to move some code out of my Blazor component into a C# class called ProgressManager.我正在构建一个 Blazor ProgressBar 演示,并且我试图将一些代码从我的 Blazor 组件移到一个名为 ProgressManager 的 C# 类中。 This is so I can abstract the code and make the ProgressManager a CascadingParameter to the ProgressBar component.这样我就可以抽象代码并使 ProgressManager 成为 ProgressBar 组件的CascadingParameter

I know how to set an EventCallback parameter for a component like this:我知道如何为这样的组件设置EventCallback参数:

[Parameter]
public EventCallback<string> UpdateNotification { get; set; }

What I don't know how to do is set this same type of property on a C# class.我不知道该怎么做是在 C# 类上设置这种相同类型的属性。

I have this code in my Start method:我的 Start 方法中有此代码:

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

The part that does not work is: this.ProgressManager.UpdateNotification = Refresh;不起作用的部分是: this.ProgressManager.UpdateNotification = Refresh;

The error is:错误是:

Cannot convert method group 'Refresh' to non-delegate type 'EventCallback'.无法将方法组“Refresh”转换为非委托类型“EventCallback”。 Did you intend to invoke the method?您是否打算调用该方法?

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

And this leads to "EventCallback cannot be applied to method group" (paraphrasing).这导致“EventCallback 不能应用于方法组”(意译)。

Turns out you can assign an event callback from C# code like this:原来你可以从 C# 代码中分配一个事件回调,如下所示:

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

void Refresh() {}

It also works with async methods, eg:它也适用于异步方法,例如:

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

ValueTask RefreshAsync() {}

UPDATE更新

You can also use EventCallbackFactory to more conveniently create event callback objects, eg:您还可以使用EventCallbackFactory更方便地创建事件回调对象,例如:

new EventCallbackFactory().Create(this, Refresh)

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

Button.Clicked = EventCallback.Factory.Create( this, ClickHandler );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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