13
votes

I'm having an issue with a basic blazor project. I have a parent component and a child component with an event callback where I want it to pass back a type of T. The issue I'm having is that I have an error about converting MethodGroup to EventCallback. If I convert this to using Action then it works but I can't do it async which isn't ideal. Any ideas what I'm doing wrong?

Parent

<Child
DeleteCallback="@OnDelete"></Child>

public async Task OnDelete(T item)
{
}

Child

@typeparam T

[Parameter]
public EventCallback<T> DeleteCallback { get; set; }

 <a @onclick="() => DeleteCallback.InvokeAsync(item)"></a>

I've added a repo here explaining the problem. Looking at the Issues for Blazor, this should;ve been fixed in 2019. https://github.com/scott-david-walker/EventCallbackError

7

7 Answers

17
votes

You were close:

<ChildComponent Item="someModel" T="SomeModel" DeleteCallback="OnDeleteSomeModel" />

@code {
    SomeModel someModel = new SomeModel();

    void OnDeleteSomeModel(SomeModel someModel)
    {
        ...
    }
}

The EventCallback uses a generic type and blazor cannot infer it if you don't pass the type to the component.

This means that if you have a EventCallback<T> you need to pass the value of T to the component e.g. T="SomeType".

19
votes

I had the same issue, nothing was wrong with my code, just closed VS and re-opened and vuala! I'm very surprised this did happen to me several times... very bad from MS!

3
votes

The following syntax worked for me:

// in the component (C#):
[Parameter]
public EventCallback<MovingEventArgs> OnMoving { get; set; }

// on the using side (Razor):
OnMoving="(Component.MovingEventArgs o) => OnMoving(o)"

// on the using side (C#):
protected void OnMoving( Component.MovingEventArgs e ) {
}

There seems to have been a change and the documentation is not up to date. This event is also using custom event arguments.

3
votes

I've experienced that the syntax was spot on and still getting this error.

Restarting Visual Studio 2019 solved the problem for me. Cleaning and rebuilding was not enough.

1
votes

For some reason Visual Studio kept a previous signature I had used. Cleaning, restarting, emptying bin/obj folders etc did not work. I had to rename the method, which worked for me.

0
votes

In my case I declared a nullable EventCallback? - you can't do that.

0
votes

In my case, the problem solved when I defined the @typeparam manually(not by inference)(TItem="int").

<MyComponent TItem="int" OnChange="Component_Changed" />