【问题标题】:How to call TapGestureRecognizer from ViewModel如何从 ViewModel 调用 TapGestureRecognizer
【发布时间】:2019-04-18 15:00:49
【问题描述】:

我正在尝试实现 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 绑定)

【问题讨论】:

标签: mvvm xamarin.forms gesture-recognition


【解决方案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
}

【讨论】:

  • 感谢您的回答...IrrigList 是 IrrigNetPage.xaml 中 ListView 的 x:name,所以我仍然有问题,因为“名称 'IrrigList' 在当前上下文中不存在”。没有 x:name 有什么解决方案如何做同样的事情吗?
  • 这个答案100%是对你原来问题的正确和完整的答案,请标记为正确。我知道这现在又带来了另一个问题,因为 IrrigList 存在于您的页面上而不是您的视图模型上。搜索命令参数。您可以通过将IrrigList 传递为CommandParameter 来解决您的新问题。看起来像这样:CommandParameter={x:Reference IrrigList}。请记住,您仍然需要更改命令才能使用参数。
  • @Knoop 你能告诉我如何更改命令吗?
  • 所以你是说你现在需要在你的 ViewModel 中访问你的 ListView?这与 MVVM 理念相矛盾。而不是访问整个模型,而是绑定要在模型中更改的属性。例如。将 IsListVisible 属性添加到您的视图模型并将 ListView 的 Visiblility 属性绑定到此属性。不要忘记这些属性需要触发 NotifyPropertyChanged 事件,以便视图了解更改
猜你喜欢
  • 2023-03-03
  • 2012-04-09
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多