trap
trap

Reputation: 2640

How to pass a funcion in Renderfragment

I want to use following Renderfragment for two different Modals. I want to pass two parameters: the heading and a function, when the BackIcon is clicked. How can I pass also the function OnVisiblityChanged?

@{
    RenderFragment <string> BackIconTitle = heading =>@<Template>
        <div class="title-with-icon">
            <div class="back-icon" @onclick="() =>OnVisiblityChanged()">
                 <ArrowLeftIcon Height="1.5rem" Width="1.5rem"/>
            </div>
            <div class="back-icon-title">@heading</div>
        </div>
    </Template>;
}

<Modal 
    Visible="@isVisible"
    TitleTemplate="@BackIconTitle(Loc["Some Heading"])" 
    Footer="@BackIconFooter"
    DestroyOnClose="true"
    OnCancel="@OnVisiblityChanged"
    Width="@("1000px")">
    <DeliveryTimeContent IsModalView="true"/>
</Modal>



private void OnVisiblityChanged()
{
  if (isVisible)
  {
    isVisible= false;
  }
  else
  {
     isVisble= true;
  }

  StateHasChanged();
}

Thank you in advance!

Upvotes: 0

Views: 740

Answers (2)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30167

I've taken your code and created a very simple page and component to demo what I believe you are trying to do.

Component.razor

A Modal is just another component.

@if(Visible)
{
    @ContentTemplate
}
@code {
    [Parameter] public RenderFragment? ContentTemplate { get; set; }
    [Parameter] public bool Visible { get; set; }
}

And then the main page.

You pass the method as a Func. You need to be precise with your definition. My function pattern conforms to the standard @onclick event pattern: Task EventMethod(MouseEventArgs e)

@page "/"

<PageTitle>Index</PageTitle>

<Component Visible="@isVisible1" ContentTemplate="@BackIconTitle("Heading1", OnVisiblity1Changed)" />

<Component Visible="@isVisible2" ContentTemplate="@BackIconTitle("Heading 2", OnVisiblity2Changed)" />

<div class="p-2 m-2">
    <button class="btn btn-primary" @onclick=OnVisiblity1Changed>
        Show/Hide 1
    </button>
    <button class="btn btn-info" @onclick=OnVisiblity2Changed>
        Show/Hide 2
    </button>
</div>

@code {
    private bool isVisible1;
    private bool isVisible2;

    RenderFragment BackIconTitle(string heading, Func<MouseEventArgs, Task> close ) => (__builder) =>
    {
        <div class="bg-dark text-white p-2 m-1 text-end">
            <button class="btn btn-primary" @onclick=close >Hide</button>
        </div>
    };


    private Task OnVisiblity1Changed(MouseEventArgs e)
    {
        isVisible1 = !isVisible1;
        return Task.CompletedTask;
    }

    private Task OnVisiblity2Changed(MouseEventArgs e)
    {
        isVisible2 = !isVisible2;
        return Task.CompletedTask;
    }
}

Upvotes: 1

David
David

Reputation: 160

Create a custom Component and use a Eventhandler that invokes on your OnVisibilityChanged Method.

Upvotes: 0

Related Questions