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;