Roland Deschain
Roland Deschain

Reputation: 2880

How to add a custom event to a blazor component?

I have created a tab control in my blazor server side application, based on a tutorial. The control works fine, however I want to be able to tell, when the active page was changed. Therefore I added a event to the code:

internal void ActivatePage(TabPage page)
{
    OnTabSelectionChanged();
    ActivePage = page;
}

public delegate void TabSelectionChangedEventHandler(object source, EventArgs args);
public event TabSelectionChangedEventHandler TabSelectionChanged;

protected virtual void OnTabSelectionChanged()
{
    TabSelectionChanged?.Invoke(this, EventArgs.Empty);
}

Now I want to do the following in my blazor component, which uses the control:

<TabControl @TabSelectionChanged="MyFunction">
    <TabPage Text="tab #1">
        <!-- content -->
    </TabPage>
    <TabPage Text="tab #2"> 
        <!-- content -->
    </TabPage>
    <TabPage Text="tab #3"> 
        <!-- content -->
    </TabPage>
</TabControl>

How would one achieve this?

Upvotes: 4

Views: 9101

Answers (1)

Caius Jard
Caius Jard

Reputation: 74730

How would a EventCallback property look like for my case above?

I was thinking not hugely dissimilar to what you have

@code{

    [Parameter]
    public EventCallback<TabPage> TabPageActivated { get; set; }

    internal async Task ActivatePage(TabPage page)
    {
        ActivePage = page;
        await TabPageActivated.InvokeAsyc(page);
    }

}

And to do the following in the blazor whatever, which uses the control:

<TabControl @TabPageActivated="MyFunction">
    <TabPage Text="tab #1">
        <!-- content -->
    </TabPage>
    <TabPage Text="tab #2"> 
        <!-- content -->
    </TabPage>
    <TabPage Text="tab #3"> 
        <!-- content -->
    </TabPage>
</TabControl>

@code{
    private async Task MyFunction(TabPage t){
      ...
    }
}

If you don't want parameter TabPage, then more like:

public EventCallback TabPageActivated { get; set; }
...

    await TabPageActivated.InvokeAsyc();
...

private async Task MyFunction(){

Upvotes: 10

Related Questions