In Blazor, the EventCallback struct is a bit different from standard events, being single-cast instead of multi-cast, etc. For that reason, I don't think this is a duplicate.
I am trying to create a set of components that all have the same [parameter] EventCallback, and it seems reasonable to use an interface to enforce that... So far this doesn't seem to be possible.
Things I've tried:
Treating this like EventHandler
public interface IResolver
{
event EventCallback Done;
}
This raises the error: Event must be a delegate type.
...And other variations on trying to make this work like an EventHandler.
Trying to use IEventCallback
EventCallback implements IEventCallback, so this seemd promising. However, it is an internal interface, and is not available to me.
Using a base class instead
This seems like it might work, but I am curious why I can't do this with an interface.
Also found:
None of that seems to be related to this problem.
Declare the Callback using the correct syntax and it will work.
Here's my test code.
using Microsoft.AspNetCore.Components;
namespace TestBlazorServer
{
public interface ICallbackComponent
{
public EventCallback MyCallBack { get; set; }
}
}
// TestCallback.razor
@namespace TestBlazorServer
@implements ICallbackComponent
<h3>TestCallback</h3>
<button class="btn btn-danger" @onclick="() => this.CallCallback()">Test Me</button>
We now declare MyCallBack
with [Parameter]
.
using Microsoft.AspNetCore.Components;
namespace TestBlazorServer
{
public partial class TestCallback : ComponentBase, ICallbackComponent
{
[Parameter] public EventCallback MyCallBack { get; set; }
private void CallCallback()
{
MyCallBack.InvokeAsync();
}
}
}
And we can declare multiple instances in index.razor
.
// index.razor
<TestCallback MyCallBack="Callback1"></TestCallback>
<TestCallback MyCallBack="Callback2"></TestCallback>
<TestCallback MyCallBack="Callback3"></TestCallback>
<div>Test:@called</div>
@code {
private string called;
private void Callback1()
=> called = "First";
private void Callback2()
=> called = "Second";
private void Callback3()
=> called = "Third";