首页 > 解决方案 > 如何使用 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 松散耦合?任何帮助,将不胜感激。

标签: c#xamlxamarin.formsprism

解决方案


在按钮上使用 EventToCommandBehavior。这将允许您利用您正在使用的任何事件上的任何事件,并在事件触发时执行命令。

<Button>
  <Button.Behaviors>
    <prism:EventToCommandBehavior EventName="Pressed"
                                  Command="{Binding PressedCommand}" />
    <prism:EventToCommandBehavior EventName="Released"
                                  Command="{Binding ReleasedCommand}" />
  </Button.Behaviors>
</Button>

请注意,如果您有某种想要传递命令的参数(可能是 EventArgs 中的属性,或者完全是您想要绑定或指定的其他东西),则可以使用其他属性。


推荐阅读