c# - 如何使用 Prism 在 Xamarin.Forms 中对按钮按下和释放事件进行松散耦合?
问题描述
对于我当前的项目,我需要在 Xamarin.Forms 中捕获按钮按下和释放事件。但我想使用 Prism 保持松散耦合。
起初我使用 的 Command 属性,如下所示:
<Button x:Name="ButtonForward" Command="{Binding MoveUpCommand}" />
但 Command 属性仅在释放按钮时触发。为了分别按下和释放操作,我使用了 XAML 中的事件:
<Button x:Name="ButtonForward" Pressed="ButtonForward_Pressed" Released="ButtonMove_Released"/>
并在后面的代码中的事件处理程序中手动调用命令:
private void ButtonMove_Released(object sender, System.EventArgs e)
{
var vm = BindingContext as DirectControlViewModel;
if (vm.MoveStopCommand.CanExecute(null))
vm.MoveStopCommand.Execute(null);
}
private void ButtonForward_Pressed(object sender, System.EventArgs e)
{
var vm = BindingContext as DirectControlViewModel;
if (vm.MoveUpCommand.CanExecute(null))
vm.MoveUpCommand.Execute(null);
}
问题是它不再是松散耦合的,因为 View 现在必须知道它的 ViewModel。有没有办法让按钮对按下和释放事件有单独的命令,保持 View 和 ViewModel 松散耦合?任何帮助,将不胜感激。
解决方案
在按钮上使用 EventToCommandBehavior。这将允许您利用您正在使用的任何事件上的任何事件,并在事件触发时执行命令。
<Button>
<Button.Behaviors>
<prism:EventToCommandBehavior EventName="Pressed"
Command="{Binding PressedCommand}" />
<prism:EventToCommandBehavior EventName="Released"
Command="{Binding ReleasedCommand}" />
</Button.Behaviors>
</Button>
请注意,如果您有某种想要传递命令的参数(可能是 EventArgs 中的属性,或者完全是您想要绑定或指定的其他东西),则可以使用其他属性。
推荐阅读
- c# - Unity3D 游戏数据库 (C#)
- c++ - 用GTK创建逻辑门模拟器,如何制作放置区?
- javascript - 使用 div 创建手风琴表
- hadoop - HDFS 块与 HDD 存储块
- doctrine-orm - 没有为类 Doctrine\ORM\PersistentCollection 定义实体管理器
- php - 如何在 IIS 8.5 中从 Web PI 卸载 php 7.0
- google-sheets - 是否可以仅使用 api 密钥发布/附加到谷歌电子表格?
- python - 运行 python cuda 程序时出错
- sql - 带有范围变量和常量的 LINQ SQL 查询
- c# - C# WebRequest TLS 1.2(请求被中止)仅第一次