代码之家  ›  专栏  ›  技术社区  ›  DarkW1nter

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

  •  0
  • DarkW1nter  · 技术社区  · 6 年前

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

      <Image.GestureRecognizers>
          <TapGestureRecognizer 
            Command="{Binding Path=BindingContext.SetImageCommand, Source={x:Reference ThePage}}"
            CommandParameter="{Binding .}"/>
      </Image.GestureRecognizers>
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Gerald Versluis    6 年前

    当然,只要用 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 到页面后面的代码,它应该可以工作。

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

    推荐文章