Xamarin.Forms 中的自定义 EventHandler 在 xaml 中不起作用

Mar*_*Law 0 c# xamarin.ios xamarin.android xamarin xamarin.forms

Xamarin.Forms,在 PCL 中,我有自定义控件,带有自定义事件:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的起始页中,我有:

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

    private void OnGridTapped(object sender, EventArgs e)
    {
        Debug.WriteLine("Tapped!");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的 XAML 看起来像这样,它可以工作:

<v:TestGrid x:Name="MainGrid" />
Run Code Online (Sandbox Code Playgroud)

但!

当我MainGrid.OnTapped += OnGridTapped; 在 xaml 中删除和添加事件时,这里:

<v:TestGrid x:Name="MainGrid" OnTapped="OnGridTapped">
Run Code Online (Sandbox Code Playgroud)

我不工作。它说..未找到 OnTapped 事件:

未处理的异常:

Xamarin.Forms.Xaml.XamlParseException:位置 6:33。未找到名称 OnTapped 的属性

我的问题是:为什么?有什么不同?

voy*_*tek 6

OnTapped 必须是一个事件:

public event EventHandler OnTapped;
Run Code Online (Sandbox Code Playgroud)