[英]Blazor attach function call to EventCallBack
I have a blazor function that is我有一个 blazor function 这是
public async Task DoSomething()
I have another class object like this:我有另一个 class object 像这样:
public class SomeClass
{
public string Title { get; set; }
public string Icon { get; set; }
public EventCallback OnClick {get;set;}
}
This class object is consumed by blazor components.此 class object 由 blazor 组件消耗。 What I would like to do is to attach the DoSomething() event to the EventBackkBack OnClick in the class object.
我想做的是将 DoSomething() 事件附加到 class object 中的 EventBackkBack OnClick。 I tried this:
我试过这个:
_collection.Add(new SomeClass{ Title = "some title", Icon = "icon", OnClick = DoSomething});
This does not work as the compiler is saying cannot convert to method group to non-delegate type EventCallBack...这不起作用,因为编译器说无法将方法组转换为非委托类型 EventCallBack ...
I can make it work if I change the property OnClick to "Action", but that requires the function call to be "async void".如果我将属性 OnClick 更改为“Action”,我可以让它工作,但这需要 function 调用为“async void”。 I cannot do that for other reasons.
由于其他原因,我不能这样做。
Is there a way for me to attach this async Task function to OnClick?有没有办法让我将此异步任务 function 附加到 OnClick? Thanks!
谢谢!
Got this the wrong way round: EventCallBack
is what you expose as a bindable property on a Razor component, not normally a property on a class.弄错了:
EventCallBack
是您在 Razor 组件上公开的可绑定属性,通常不是 class 上的属性。
Chris Sainty shows how this works in this article: https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/ Chris Sainty 在本文中展示了其工作原理: https://chrissinty.com/3-ways-to-communicate-between-components-in-blazor/
In the first example his component has a bindable property在第一个示例中,他的组件具有可绑定属性
[Parameter] public EventCallback<string> OnClick { get; set; }
This tells someone using the component that it will send an event with a string parameter.这告诉使用该组件的人它将发送带有字符串参数的事件。 This can be bound to a method, which he shows next:
这可以绑定到一个方法,他接下来会展示:
<ChildComponent OnClick="ClickHandler"></ChildComponent>
<p>@message</p>
@code {
string message = "Hello from ParentComponent";
void ClickHandler(string newMessage)
{
message = newMessage;
}
}
Note that the bound method, ClickHandler
is not async.请注意,绑定方法
ClickHandler
不是异步的。 Blazor supports both async and sync calls, it could also be Blazor 支持异步和同步调用,也可以是
async Task ClickHandler(string newMessage)
{
message = await SomeAsyncMethod(newMessage);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.