在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);
}
}
在我的StartPage中我有:
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看起来像这样,并且有效:
<v:TestGrid x:Name="MainGrid" />
BUT!
删除MainGrid.OnTapped += OnGridTapped;
时
并在xaml中添加事件,这里:
<v:TestGrid x:Name="MainGrid" OnTapped="OnGridTapped">
我不行。它说..未找到OnTapped事件:
未处理的例外:
Xamarin.Forms.Xaml.XamlParseException:位置6:33。没有财产 名称OnTapped发现
我的问题是:为什么?有什么区别?
答案 0 :(得分:4)
OnTapped
必须是一个事件:
public event EventHandler OnTapped;