0
votes

I have a blazor function that is

public async Task DoSomething()

I have another class object like this:

public class SomeClass
{
    public string Title { get; set; }
    public string Icon { get; set; }
    public EventCallback OnClick {get;set;}
}

This class object is consumed by blazor components. What I would like to do is to attach the DoSomething() event to the EventBackkBack OnClick in the class object. I tried this:

_collection.Add(new SomeClass{ Title = "some title", Icon = "icon", OnClick = DoSomething});

This does not work as the compiler is saying cannot convert to method group to non-delegate type EventCallBack ...

I can make it work if I change the property OnClick to "Action", but that requires the function call to be "async void". I cannot do that for other reasons.

Is there a way for me to attach this async Task function to OnClick? Thanks!

1
What you mean, I upvoted one just two days ago ... - Franky

1 Answers

2
votes

Got this the wrong way round: EventCallBack is what you expose as a bindable property on a Razor component, not normally a property on a class.

Chris Sainty shows how this works in this article: https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/

In the first example his component has a bindable property

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

This tells someone using the component that it will send an event with a string parameter. This can be bound to a method, which he shows next:

<ChildComponent OnClick="ClickHandler"></ChildComponent>

<p>@message</p>

@code {

    string message = "Hello from ParentComponent";

    void ClickHandler(string newMessage)
    {
        message = newMessage;
    }

}

Note that the bound method, ClickHandler is not async. Blazor supports both async and sync calls, it could also be

    async Task ClickHandler(string newMessage)
    {
        message = await SomeAsyncMethod(newMessage);
    }