3

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
  • 1
    What you mean, I upvoted one just two days ago ... Commented Apr 6, 2021 at 14:16

1 Answer 1

4

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);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the advice, will give it a shot!
In case you want to attach in code and not in markup, you have to use something like MyComponentRef.OnClick = EventCallback.Factory.Create<string>(this, ClickHandler).
@UweKeim thank you, I needed this. I am dynamically rendering a component that has an EventCallback. Without the EventCallback.Factory, I couldn't get the parameter to work correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.