Custom EventHandler in Xamarin.Forms doesn't w

2019-09-16 18:06发布

问题:

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?

回答1:

OnTapped must be an event:

public event EventHandler OnTapped;