如何在堆栈布局或框架中添加Click事件 [英] How to Add Click event in Stack Layout or Frame
问题描述
我是xamarin.forms的新手,请帮助我如何在堆栈布局或框架中添加点击事件
I am new in xamarin.forms please help me out how i can add click event in Stack Layout or Frame
<Frame Grid.Column="0" BackgroundColor="#ffffff" Grid.Row="0" HasShadow="true" OutlineColor = "Black">
</Frame>
<StackLayout Grid.Column="0" BackgroundColor="#313FA0" Grid.Row="0">
</StackLayout>
推荐答案
您可以像这样将TapGestureRecognizer添加到XAML中的StackLayout:
You can add a TapGestureRecognizer to the StackLayout in XAML like this:
<StackLayout Grid.Column="0" Grid.Row="0" BackgroundColor="#313FA0">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="OnTapped"/>
</StackLayout.GestureRecognizers>
</StackLayout>
然后,您可以在后面的代码中实现 OnTapped 方法:
Then you can implement the OnTapped method in the code behind:
void OnTapped(object sender, EventArgs e)
{
// Do stuff
}
或者,如果您使用的是MVVM模式,并且希望将分接头绑定到ViewModel中的ICommand,则可以这样实现:
Alternatively, if you are using the MVVM pattern and would like to Bind the tap to an ICommand in the ViewModel, that can be achieved like this:
<StackLayout Grid.Column="0" Grid.Row="0" BackgroundColor="#313FA0">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TapCommand}"/>
</StackLayout.GestureRecognizers>
</StackLayout>
在ViewModel中,您将:
In your ViewModel you would have:
private ICommand _tapCommand;
pubic ICommand TapCommand => (_tapCommand ?? _tapCommand = new Command(OnTapped));
void OnTapped()
{
// Do stuff
}
Xamarin网站上有一些非常好的指南:
There are some really good guides on the Xamarin website:
http://developer.xamarin .com/guides/cross-platform/xamarin-forms/working-with/gestures/#Using_Xaml
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/gestures/tap/
这篇关于如何在堆栈布局或框架中添加Click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!