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

 ̄綄美尐妖づ 提交于 2019-12-12 02:33:33

问题


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;


来源:https://stackoverflow.com/questions/42848585/custom-eventhandler-in-xamarin-forms-doesnt-work-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!