简体   繁体   中英

Custom EventHandler in Xamarin.Forms doesn't work in xaml

In Xamarin.Forms , in PCL, I have custom control, with custom event:

public class TestGrid : Grid
{
    public EventHandler OnTapped;

    public TestGrid()
    {
        var tgr = new TapGestureRecognizer { NumberOfTapsRequired = 1 };
        tgr.Tapped += Tgr_Tapped;
        this.GestureRecognizers.Add(tgr);
    }

    private void Tgr_Tapped(object sender, EventArgs e)
    {
        OnTapped?.Invoke(sender, e);
    }
}

in my StartPage I have:

public partial class StartPage : ContentPage
{
    public StartPage()
    {
        InitializeComponent();
        BindingContext = new StartPageViewModel();
        MainGrid.OnTapped += OnGridTapped;
    }

    private void OnGridTapped(object sender, EventArgs e)
    {
        Debug.WriteLine("Tapped!");
    }
}

My XAML looks like that, and it works:

<v:TestGrid x:Name="MainGrid" />

BUT!

when I remove MainGrid.OnTapped += OnGridTapped; and add event in xaml, here:

<v:TestGrid x:Name="MainGrid" OnTapped="OnGridTapped">

I doens't work. It says.. OnTapped event not found:

Unhandled Exception:

Xamarin.Forms.Xaml.XamlParseException: Position 6:33. No Property of name OnTapped found

My question is: Why? What's the difference?

OnTapped必须是一个事件:

public event EventHandler OnTapped;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM