如何从渲染片段 Blazor 中的静态上下文调用方法

问题描述 投票:0回答:1

我有一个分配为菜单的渲染片段,我需要能够清除该渲染片段中的列表,但我似乎无法让它工作。我尝试过事件回调、操作、延迟,每次遇到此错误时:关键字“this”在当前上下文中不可用。我也无法通过构建器传递任何参数,它给了我这个错误:无法将初始化类型“lambda 表达式”转换为目标类型“Microsoft.AspNetCore.Components.RenderFragment”。那么在这种情况下我怎样才能清除这个列表呢?问题出在按钮内:ClearListAction()。这也不起作用:OnCLick=(() => webhookList.Clear()) 我得到了关于“this”的相同错误。

    public delegate void ClearWebhooksAction(); // Delegate for clearing

    public static ClearWebhooksAction ClearListAction { get; set; } // Delegate reference

    public RenderFragment menu =
        @<Menu>

            @foreach (var n in webhookList)
            
                    <div class="flex">
                        <div style="flex:20%">
                            <Avatar size="40px" src="@n.Avatar"/>
                        </div>
                        <div style="flex:65%">@n.Subtitle</div>
                    </div>
            }
            @if (webhookList.Count > 0)
            {
                ClearListAction = () => webhookList.Clear();
                <div class="dismiss">
                   <MudButton  OkClick="@(() => webhookList.Clear())">Dismiss</MudButton>
                </div>
            }
    </Menu>;

它在我的 blazor 代码中是这样传递的:

 <Dropdown Overlay=@menu Placement="AntDesign.Placement.Bottom" Class="notifications" Arrow>
                    <MudBadge Content="@(notificationCount)" Color="MudBlazor.Color.Primary" Overlap="true" Origin="Origin.CenterRight">
                        <Icon Type="bell" Theme="outline" OnClick="() => OpenDrawer(MudBlazor.Anchor.End)"/>
                    </MudBadge>
                </Dropdown>
static blazor ant-design-pro ant-design-blazor
1个回答
0
投票

这需要一段奇怪的 C# 语法。

有效的是(注意双

=>
):

public ClearWebhooksAction ClearListAction { get; set; } // not static



public RenderFragment menu =>  () => 

   @<Menu>  
     ... // as before
      <MudButton  OkClick="@(() => ClearListAction())">Dismiss</MudButton>
   </Menu>;

如果没有参数,您可以将其缩短为:

OkClick="ClearListAction"

© www.soinside.com 2019 - 2024. All rights reserved.