简体   繁体   中英

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?

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(){

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