xamarin表单-将TapGestureRecognizer绑定到代码隐藏而不是视图模型

时间:2018-11-15 14:38:55

标签: c# xaml xamarin.forms

我意识到这打破了MVVM模式,但是有可能将TapGestureRecognizer绑定到XAML.cs代码后面的方法而不是视图模型吗?

  <Image.GestureRecognizers>
      <TapGestureRecognizer 
        Command="{Binding Path=BindingContext.SetImageCommand, Source={x:Reference ThePage}}"
        CommandParameter="{Binding .}"/>
  </Image.GestureRecognizers>

1 个答案:

答案 0 :(得分:3)

当然,只需使用Tapped事件。

<TapGestureRecognizer Tapped="Thing_Tapped" />

并在您的代码隐藏中:

public void Thing_Tapped (object sender, EventArgs args)
{
   // Do your thing
}

也许乍一看,您的意思是如果您可以将Command绑定到隐藏代码中的某些内容。我尚未对其进行测试,但看起来它应该可以与您的代码一起使用并进行较小的调整,只需执行以下操作即可:

<Image.GestureRecognizers>
      <TapGestureRecognizer Command="{Binding Path=SetImageCommand, Source={x:Reference ThePage}}" CommandParameter="{Binding .}"/>
</Image.GestureRecognizers>

注意如何将BindingContext.从绑定中删除。这意味着它已绑定到页面的BindingContext属性。您当然也可以绑定到其他属性。现在,您只需将SetImageCommand移到页面的代码后面即可,它应该可以工作。

无论哪种方式,您现在都可以从页面而不是视图模型中触发逻辑。

相关问题