【问题标题】:How to pass EventArgs to DelegateCommand?如何将 EventArgs 传递给 DelegateCommand?
【发布时间】:2017-08-16 23:59:54
【问题描述】:

我有一个Xamarin.Forms 项目。在 Prism 中作为 MVVM 框架。我有一个自定义控件(源自CocosSharpView,但这并不重要)。我正在使用参数在该类中引发自定义事件,但无法将此参数传输到 ViewModel。代码如下:

查看部分。我正在启动一个带有一些参数的 custom OnTouched 事件:

public class CustomCocosSharpView : CocosSharpView
{
    public event EventHandler<CustomEventArgs> OnTouched;
    public CCGameView gameView;

    // ... not important stuff ...

    private void OnViewCreated(object sender, EventArgs ea)
    {
        if (gameView == null)
        {
            gameView = sender as CCGameView;
            if (gameView != null)
            {
                _gameScene = new GameScene(gameView);
                _gameScene.OnTouched += (s, e) =>
                {
                    CustomEventArgs custom = new CustomEventArgs() { Foo = 4 };
                    OnTouched?.Invoke(s, custom);
                };
                gameView.RunWithScene(_gameScene);
            }
        }
        OnCreated?.Invoke(sender, ea);
    }
}

public class CustomEventArgs : EventArgs
{
    public int Foo { get; set; }
}

XAML部分:

  <mobile:CustomCocosSharpView>
    <behaviors:Interaction.Behaviors>
      <behaviors:BehaviorCollection>
        <behaviors:EventToCommand EventName="OnTouched"
                                  Command="{Binding OnTouchedCommand}" />        
      </behaviors:BehaviorCollection>
    </behaviors:Interaction.Behaviors>
  </mobile:CustomCocosSharpView>

最后是 ViewModel

    private DelegateCommand<CustomEventArgs> onTouchedCommand;
    public DelegateCommand<CustomEventArgs> OnTouchedCommand
    {
        get
        {
            return onTouchedCommand ?? (onTouchedCommand = new DelegateCommand<CustomEventArgs>((arg) =>
            {
                Debug.WriteLine("OnTouchCommand " + arg?.Foo.ToString()); //arg is null. Why?
            }));
        }
    }

问题:

如何在 DelegateCommand 中获取 CustomEventArgs 参数? 一定可以!但没有任何效果:/

感谢您的帮助!

【问题讨论】:

标签: c# xamarin mvvm xamarin.forms prism


【解决方案1】:

如果您使用的是 Prism 6.3-pre2,您可以使用内置的 EventToCommand 并使用转换器或路径完全控制传递给 DelegateCommand 的内容。你可以在这里查看文档:http://prismlibrary.readthedocs.io/en/latest/Xamarin-Forms/6-EventToCommandBehavior/#using-the-eventtocommandbehavior

【讨论】:

  • 谢谢布赖恩,我会在今天晚些时候尝试。看起来不错。顺便提一句。可以肯定的是,在6.2.0 版本中是否有可能(将参数从自定义事件传递到命令)?这就是我现在正在使用的
  • 不使用 Prism。 6.2 没有 Prism EventToCommand 行为。
  • 等等,什么?我发布的代码是使用 6.2.0 编译和运行的。实际上这是nuget的最新版本。 Prism 6.2.0 中肯定有EventToCommand。我不知道参数 - 我将能够测试它 c.a. 4个小时。顺便提一句。如果不在 nuget 上,我从哪里获得 6.3?
  • 您确定您使用的是 Prism 的 EventToCommand 而不是其他的吗?我在 6.3 的发行说明中添加了 EventToCommand。 6.3 目前处于预览阶段,只有包含预览包才能看到。
  • 哦!我想你是正确的!我完全忘记了我之前安装了Corcav.Behaviors。所以从技术上讲,如果我将Prism.CorePrism.Forms 更新到6.3,我可以删除Corcav.Behaviors
猜你喜欢
  • 2016-12-25
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 2020-05-07
相关资源
最近更新 更多