如何从ViewModel调用TapGestureRecognizer

问题描述 投票:0回答:1

我正在尝试实现TapGestureRecognizer,它将在ViewModel(xaml.cs)中调用而不是在View类中...

以下是xaml文件中的示例代码:(IrrigNetPage.xaml)

 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:i18n="clr-namespace:agroNet.AppResource;assembly=agroNet"
         xmlns:viewModels="clr-namespace:agroNet.ViewModel"
         x:Class="agroNet.View.IrrigNetPage"
         BackgroundColor="#EBEBEB">

    <Grid>
        <Grid.GestureRecognizers>
            <TapGestureRecognizer Tapped="HideListOnTap"/>
        </Grid.GestureRecognizers>
    </Grid>

我在xaml.cs页面(视图)中实现了HideListOnTap,如下所示:(IrrigNetPage.xaml.cs)

    int visibility = 1;
    private void HideListOnTap(object sender, EventArgs e)
    {
        visibility++;
        if ((visibility % 2) == 0)
        {
            IrrigList.IsVisible = false;
        }
        else
        {
            IrrigList.IsVisible = true;
        }
    }

它工作正常,但如何在ViewModel中做同样的事情? (如何将(IrrigNetPage.xaml)的Gesture识别器与IrrigNetViewModel中的HideListOnTap绑定)

mvvm xamarin.forms gesture-recognition
1个回答
1
投票

只要您想在ViewModel中处理某些事件,请使用Command。如果不传递任何参数,代码将如下所示

<!-- in IrrigNetPage.xaml -->

<TapGestureRecognizer Command="{Binding HideListOnTapCommand}"/>

并在ViewModel IrrigNetPageViewModel.cs中

public ICommand HideListOnTapCommand { get; } 

public IrrigNetPageViewModel()
{
   HideListOnTapCommand = new Command(HideListOnTap); 
   // if HideListOnTap is async create your command like this
   // HideListOnTapCommand = new Command(async() => await HideListOnTap());

}

private void HideListOnTap()
{
   // do something
}
© www.soinside.com 2019 - 2024. All rights reserved.