【问题标题】:xamarin forms - bind TapGestureRecognizer to code-behind rather than view modelxamarin 表单 - 将 TapGestureRecognizer 绑定到代码隐藏而不是视图模型
【发布时间】:2018-11-15 14:38:55
【问题描述】:

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

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

【问题讨论】:

    标签: c# xaml xamarin.forms


    【解决方案1】:

    当然,只需使用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 移动到您页面的代码隐藏中,它应该可以工作了。

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

    【讨论】:

    • 添加了更多内容,以防您仍然想使用该命令 :-),谢谢!
    • 如果您不介意还有一件事?如果我确实使用了 Tapped 选项,我可以将 Tapped 对象作为参数传递给被调用的代码吗?
    • 不是很容易。 sender 参数应该是 TapGestureRecognizer。因此,您可以执行以下操作:((TapGestureRecognizer)sender).CommandParameter,前提是您仍将值放在 CommandParameter 属性中。
    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    相关资源
    最近更新 更多