Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add Click event in Stack Layout or Frame

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> 
like image 545
Atul Dhanuka Avatar asked Jun 19 '15 09:06

Atul Dhanuka


2 Answers

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> 

Then you can implement the OnTapped method in the code behind:

void OnTapped(object sender, EventArgs e)  {     // Do stuff } 

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> 

In your ViewModel you would have:

private ICommand _tapCommand; pubic ICommand TapCommand => (_tapCommand ?? _tapCommand = new Command(OnTapped));  void OnTapped()  {     // Do stuff } 

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/

like image 194
pnavk Avatar answered Sep 23 '22 08:09

pnavk


Well, thanks @pnavk , according to what i saw, allow me also to share this, the Views (Layouts,Frame,Images etc) which do not have the inbuilt OnClick or Click Events have the same way of tackling the click Event.

As follows :

For an Image:

<Image>    <Image.GestureRecognizers>        <TapGestureRecognizer Tapped="onImageCitizenReporterTapped" NumberOfTapsRequired="1" />    </Image.GestureRecognizers> </Image> 

For a Frame :

<Frame>    <Frame.GestureRecognizers>        <TapGestureRecognizer Tapped="onFrameCitizenReporterTapped" NumberOfTapsRequired="1" />    </Frame.GestureRecognizers> </Frame> 

For StackLayout :

<StackLayout>    <StackLayout.GestureRecognizers>        <TapGestureRecognizer Tapped="onStackCitizenReporterTapped" NumberOfTapsRequired="1" />    </StackLayout.GestureRecognizers> </StackLayout > 

Cheers.

like image 33
Lutaaya Huzaifah Idris Avatar answered Sep 24 '22 08:09

Lutaaya Huzaifah Idris