How to both execute Command and Button click in Xamarin

Issue

I have:

<Grid.GestureRecognizers>
  <TapGestureRecognizer NumberOfTapsRequired"1" Command"{Binding Source{RelativeSource AncestorType{x:Type locals:OneViewModel}}, 
PathOneTappedView}" CommandParameter"{Binding .}" />
</Grid.GestureRecognizers>

<Button x:Name"bt_one" Clicked"bt_one_Clicked"/>

When I do Grid Tap, Command and bt_one_Clicked execute concurrently? Thank you

Solution

When I do Grid Tap, Command and bt_one_Clicked execute concurrently?

Yes, you can add the button’s clicked code in your grid tap event when tapping your grid.

You can refer to the following code:

OnePage.xml

<?xml version"1.0" encoding"utf-8" ?>
<ContentPage xmlns"http://xamarin.com/schemas/2014/forms"
             xmlns:x"http://schemas.microsoft.com/winfx/2009/xaml" xmlns:formapp1"clr-namespace:FormApp1"
             x:Class"FormApp1.OnePage">

    <ContentPage.BindingContext>
        <formapp1:OneViewModel></formapp1:OneViewModel>
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>
            <Grid WidthRequest"300" HeightRequest"600" BackgroundColor"Yellow">

                <Grid.GestureRecognizers>
                    <TapGestureRecognizer NumberOfTapsRequired"1"  Command"{Binding OneTappedViewCommand}"  />
                </Grid.GestureRecognizers>
            </Grid>

            <Button x:Name"bt_one" Text"one button" Command"{Binding BtnOneClickedCommand}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

OneViewModel.cs

 public class OneViewModel: INotifyPropertyChanged
{
    public ICommand OneTappedViewCommand { private set; get; }

    public ICommand BtnOneClickedCommand { private set; get; }

    public OneViewModel() {

        OneTappedViewCommand  new Command(GridTapped);
        BtnOneClickedCommand new Command(btnOneClickedMthod);
    }

    private void GridTapped()
    {
        System.Diagnostics.Debug.WriteLine("----111------> GridTapped is triggered......");


        //add one clicked method here 
        btnOneClickedMthod();
    }

    private void btnOneClickedMthod()
    {
        System.Diagnostics.Debug.WriteLine("----222------> GridTapped is triggered......");
    }


    bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName  null)
    {
        if (Object.Equals(storage, value))
            return false;

        storage  value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName  null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Note:

In model OneViewModel, you can add bt_one event(btnOneClickedMthod) in grid tap function GridTapped.

Answered By – Jessie Zhang -MSFT

Leave a Comment