Joe Munkyung
Joe Munkyung

Reputation: 35

How to pass callback method from xaml? (Xamarin.form & WPF)

I'm making my custom image button on Xamarin form. 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? And How do you call that technique?

Thanks.

myxaml.xaml

<local:CircleImageButton buttonCallback="buttonCallback"...

myxaml.xaml.cs

void buttonCallback()
{
...
}

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();
                })
            });     
        }
    }
}

Upvotes: 2

Views: 2268

Answers (2)

nicensee
nicensee

Reputation: 101

A brief addition to Sven's answer (as I am not yet allowed to comment); if you wish to use custom EventArgs in order to pass back customizable information, you must use:

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 :)

Upvotes: 0

Sven-Michael St&#252;be
Sven-Michael St&#252;be

Reputation: 14750

Just change your code to:

public event ClickedDelegate buttonCallback;

Suggestion

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)
{

}

Upvotes: 7

Related Questions