【问题标题】:How to do loose coupling of button pressed and released events in Xamarin.Forms with Prism?如何使用 Prism 在 Xamarin.Forms 中对按钮按下和释放事件进行松散耦合?
【发布时间】:2020-02-06 10:38:44
【问题描述】:

对于我当前的项目,我需要在 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 松散耦合?任何帮助将不胜感激。

【问题讨论】:

  • 为什么不像正常的 (wpf-)xaml 那样使用行为?

标签: c# xaml xamarin.forms prism


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-18
    • 2017-04-11
    • 1970-01-01
    • 2015-02-15
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多