如何从 ViewModel 调用 TapGestureRecognizer
How to call TapGestureRecognizer from ViewModel
我正在尝试实现将在 ViewModel (xaml.cs) 中调用的 TapGestureRecognizer,而不是在 View class...
下面是 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 绑定)
每当您想处理 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
}
我正在尝试实现将在 ViewModel (xaml.cs) 中调用的 TapGestureRecognizer,而不是在 View class...
下面是 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 绑定)
每当您想处理 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
}