How to add a click handler to a content page in xamarin formats

I am new to Xamarin.Forms and am trying to add a click event to my content page. I want the event to start when the user clicks on the page, no matter where.

I created similar functionality in a WinPhone application where I could solve my problem with OnLeftMouseButtonDown that was available on PhoneApplicationPage, but I could not find a suitable copy in ContentPage. Any suggestions?

+3


source to share


1 answer


To get this working you need to add Layout to ContentPage as you want to specify some content and set Horizontal Buttons and VerticalOptions to LayoutOptions.FillAndExpand .

This is not enough, although handle the taps correctly.

You also need to specify the BackgroundColor for the Layout . I have set Color.Transparent for me . If you try without specifying Color , it doesn't work .

Next, you need to attach a TapGestureRecognizer to the ContentPage to catch the clicks made.



While this works well with Labels and Buttons in my test below, still getting TapGestures for WindowsPhone on both types along with firing a button click event - this doesn't completely work with Android , as the Button will prevent the TapGesture event from firing.

Another alternative is to try to put an invisible ' Grid on top of everything. However, the problem with this approach is that you will lose your Click event handler when firing with WindowsPhone , and also lose your Click event handler when Android starts . However, the good part is that you can detect the click anywhere, although don't miss it. It just depends on what you are trying to achieve at the end of the day.

StackLayout objStackLayout = new StackLayout()
{
    Orientation = StackOrientation.Horizontal,
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand,
    BackgroundColor = Color.Transparent
};
//
Label objLabel1 = new Label();
objLabel1.BackgroundColor = Color.Red;
objLabel1.Text = "label1";
objLabel1.HorizontalOptions = LayoutOptions.Start;
objLabel1.VerticalOptions = LayoutOptions.Start;
objLabel1.WidthRequest = 100;
objLabel1.HeightRequest = 300;
objStackLayout.Children.Add(objLabel1);
//
Label objLabel2 = new Label();
objLabel2.BackgroundColor = Color.Green;
objLabel2.Text = "label2";
objLabel2.Font = Font.OfSize("Arial", 48);
objLabel2.WidthRequest = 100;
objLabel2.HeightRequest = 300;
objStackLayout.Children.Add(objLabel2);
//
Button objButton1 = new Button();
objButton1.Text = "Click Me";
objButton1.WidthRequest = 300;
objButton1.HeightRequest = 300;
objStackLayout.Children.Add(objButton1);
//
this.Content = objStackLayout;


TapGestureRecognizer objTapGestureRecognizer1 = new TapGestureRecognizer();
objTapGestureRecognizer1.Tapped += ((o2, e2) =>
    {
        System.Diagnostics.Debug.WriteLine("Clicked!");
    });

this.Content.GestureRecognizers.Add(objTapGestureRecognizer1);

      

+5


source







All Articles