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. This is so I can abstract the code and make the ProgressManager a CascadingParameter
to the ProgressBar component.
I know how to set an EventCallback
parameter for a component like this:
[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.
I have this code in my Start method:
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;
The error is:
Cannot convert method group 'Refresh' to non-delegate type 'EventCallback'. Did you intend to invoke the method?
I also tried: this.ProgressManager.UpdateNotification += Refresh;
And this leads to "EventCallback cannot be applied to method group" (paraphrasing).
Turns out you can assign an event callback from C# code like this:
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:
new EventCallbackFactory().Create(this, Refresh)
您还可以使用以下代码通过工厂创建EventCallBack
,而无需新建EventCallbackFactory
Button.Clicked = EventCallback.Factory.Create( this, ClickHandler );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.