Xamarin.Forms中的自定义EventHandler在xaml中不起作用 [英] Custom EventHandler in Xamarin.Forms doesn't work in xaml

查看:226
本文介绍了Xamarin.Forms中的自定义EventHandler在xaml中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!");
    }
}

我的XAML看起来像这样,并且可以正常工作:

My XAML looks like that, and it works:

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

但是!

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

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

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

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

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

未处理的异常:

Unhandled Exception:

Xamarin.Forms.Xaml.XamlParseException:位置6:33.无属性 找到名字OnTapped

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;

这篇关于Xamarin.Forms中的自定义EventHandler在xaml中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆