简体   繁体   中英

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.

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;

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();
    }                
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM