如何在Xamarin中同时执行命令和按钮单击



我有:

<Grid.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding Source={RelativeSource AncestorType={x:Type locals:OneViewModel}}, 
Path=OneTappedView}" CommandParameter="{Binding .}" />
</Grid.GestureRecognizers>
<Button x:Name="bt_one" Clicked="bt_one_Clicked"/>

当我做Grid Tap,命令和bt_one_Clicked并发执行?谢谢你

当我做Grid Tap, Command和bt_one_Clicked并发执行?

是的,当你点击网格时,你可以在网格点击事件中添加按钮的点击代码。

你可以参考下面的代码:

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;
}

注意:

OneViewModel模型中,可以在栅格分接函数GridTapped中增加bt_one事件(btnOneClickedMthod)。

最新更新