我正在尝试实现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)中的手势识别器与IrrigNetViewModel中的HideListOnTap绑定)
答案 0 :(得分: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
}