americanslon
americanslon

Reputation: 4298

Check if EventCallback has been set Blazor

Is there a way to check if EventCallback has been set to something. I am setting mine outside the component and only want to show certain things inside the component if the EventCallback has been set.

Upvotes: 34

Views: 9171

Answers (2)

user12228709
user12228709

Reputation:

EventCallBack is a Struct. I was expecting the same thing, such as a way to check if EventCallBack is not null, but since it is a struct, EventCallback.InvokeAsync() won't raise an error if not set, which defies my C# compiler in my brain.

In this example here, if the error handler is not set to something, the exception is never thrown since a Struct cannot be null. Kind of defies logic to me, but it has nothing to call so an error is not thrown.

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

private void ResetFinished()
{  
    try
    {
        // Notify the client the Reset button was clicked.
        OnReset.InvokeAsync("Reset");
    }
    catch (Exception error)
    {
        // for debugging only
        string err = error.ToString();
    }                
}

Upvotes: 1

Rob
Rob

Reputation: 1567

You can use the HasDelegate property on the EventCallback parameter. This will return a bool indicating whether the event dispatcher is non null

[Parameter]
public EventCallback DoSomething { get; set; }

private bool IsEventSet => DoSomething.HasDelegate;

Upvotes: 51

Related Questions