[英]How to pass callback method from xaml? (Xamarin.form & WPF)
I'm making my custom image button on Xamarin form.我正在 Xamarin 表单上制作我的自定义图像按钮。 But below my code is not working.但是下面我的代码不起作用。
runtime error message :运行时错误消息:
Position 26:34. Cannot assign property "buttonCallback": type mismatch between "System.String" and "XXX.CircleImageButton+ClickedDelegate"
What's the right way to pass callback method from xaml?从 xaml 传递回调方法的正确方法是什么? And How do you call that technique?你怎么称呼这种技术?
Thanks.谢谢。
myxaml.xaml myxaml.xaml
<local:CircleImageButton buttonCallback="buttonCallback"...
myxaml.xaml.cs myxaml.xaml.cs
void buttonCallback()
{
...
}
CircleImageButton.cs CircleImageButton.cs
using System;
using ImageCircle.Forms.Plugin.Abstractions;
using Xamarin.Forms;
namespace XXX
{
public class CircleImageButton : CircleImage
{
public delegate void ClickedDelegate();
public ClickedDelegate buttonCallback { set; get; }
public CircleImageButton ()
{
this.GestureRecognizers.Add (new TapGestureRecognizer{
Command = new Command(() => {
this.Opacity = 0.6;
this.FadeTo(1);
this.buttonCallback();
})
});
}
}
}
Just change your code to:只需将您的代码更改为:
public event ClickedDelegate buttonCallback;
For custom events, I'd use this structure:对于自定义事件,我会使用这种结构:
MyBarElement我的栏元素
Decalaration声明
public event EventHandler FooHappend;
Invocation调用
FooHappend?.Invoke(this, EventArgs.Empty);
Page页面
Then you can use然后你可以使用
<MyBarElement FooHappend="OnFooHappend"></MyBarElement>
In your code behind在你后面的代码中
private void OnFooHappend(object sender, EventArgs eventArgs)
{
}
A brief addition to Sven's answer (as I am not yet allowed to comment);对 Sven 的回答的简短补充(因为我还不能发表评论); if you wish to use custom EventArgs in order to pass back customizable information, you must use:如果您希望使用自定义 EventArgs 来传回可自定义的信息,您必须使用:
public event EventHandler<CustomEventArgs> FooHappend;
along with:连同:
FooHappend?.Invoke(this, new CustomEventArgs(MyValue.ToString()));
and:和:
private void OnFooHappend(object sender, CustomEventArgs eventArgs)
{
}
which you can easily define like so:您可以像这样轻松定义:
public class CustomEventArgs: EventArgs
{
private readonly string customString;
public CustomEventArgs(string customString)
{
this.customString= customString;
}
public string CustomString
{
get { return this.customString; }
}
}
Hope this saves someone an hour or two down the road :)希望这可以为某人节省一两个小时的时间:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.