共享 Blazor 组件中的按钮和自定义事件处理程序列表

List of buttons and custom event Handlers in a shared blazor component

我对这个已经束手无策了,我一直在网上寻找各种方法,但似乎没有任何进展。

我有一个共享组件,在本例中是一个模仿 Web 表单时代列表视图的组件。我希望任何未来的开发人员都能在项目中实现列表视图,并能够构建一组自定义按钮以附加到每一行(这一点我可以正常工作)。我遇到的问题是能够将自定义 Action 处理程序分配给每个按钮以 运行 列表视图的父组件上的方法。我有一个 class 这样的:

using System;

namespace Speedy.Razor.SharedComponents.WebFormComponents.Shared
{
    public class CustomAction
    {
        public string Name { get; set; }

        public string Icon { get; set; }

        public Action<int> OnClick { get; set; }
    }
}

我正在将其应用到这样的行:

foreach (var customAction in CustomActions)
{
   <span class="@customAction.Icon" @onclick='() => customAction.OnClick(obj.Id)'></span>
}

效果不错。

然后我尝试创建自定义操作列表,如下所示:

List<CustomAction> customActions = new List<CustomAction>()
{
    new CustomAction {Name = "Edit", Icon="oi oi-pencil", OnClick =  },
    new CustomAction {Name = "Contacts", Icon="oi oi-person", OnClick = }
};

我已经尝试过委托,但似乎无法触发所需的方法,除非它是静态的,而我不想要这样;或者我需要创建对 class 的引用,这会导致 Blazor 中出现问题,因为对组件上的 class 的新引用会导致 StateHasChanged 失败。

有什么想法吗?

谢谢

这是有效的...复制并运行它。如果你有,请提问,因为我不确定我应该在这里解释什么。

Index.razor

@page "/"

@foreach (var customAction in customActions)
{
count++;
<span class="@customAction.Icon" @onclick="@(() => 
 customAction.OnClick(count))"></span>
}

@code{
List<CustomAction> customActions;

private int count = 10;


private void myclick(int myint)
{
    Console.WriteLine(myint.ToString());
}

private void myclick2(int myint)
{
    Console.WriteLine(myint.ToString());
}

protected override void OnInitialized()
{
    customActions = new List<CustomAction>()
{
    new CustomAction {Name = "Edit", Icon="oi oi-pencil", OnClick = myclick  
},
    new CustomAction {Name = "Contacts", Icon="oi oi-person", OnClick = 
  myclick2} };

    base.OnInitialized();
}
}

assign a custom Action handler to each button to run a method on the parent component of the list view

假设customActions也是那个父组件的成员,定义同级的方法即可:

List<CustomAction> customActions = new List<CustomAction>()
{
    new CustomAction {Name = "Edit", Icon="oi oi-pencil", OnClick = ClickHandler },
    new CustomAction {Name = "Contacts", Icon="oi oi-person", OnClick = ClickHandler }
};

void ClickHandler(int id)
{
   ... 
}

感谢您的回复,它真的很简单,在看了您的示例之后,我意识到我遇到这些问题的原因,这在我最初的问题中并不明显。我试图在无法访问 class.

中的非静态方法的方法之外初始化列表

再次感谢您帮我发现这个问题!