c# - 如何将 EventArgs 传递给 DelegateCommand?

标签 c# xamarin mvvm xamarin.forms prism

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

查看部分。我正在使用一些参数启动一个自定义 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 参数? 这一定是可能的!但没有任何效果:/

感谢您的帮助!

最佳答案

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

关于c# - 如何将 EventArgs 传递给 DelegateCommand?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992860/

相关文章:

javascript - 文件 uploader 调用函数

xamarin - 如何使用 Azure 移动服务(使用 Xamarin.Auth?)?

wpf - Prism 和 View 的多个实例

windows-phone-7 - 使用 MVVM 从 ListBox 中删除项目

Xamarin.Forms 中的 Android CoordinatorLayout

wpf - 什么构成 View 模型?

c# - 如何通过 ObjectDataProvider 将 ComboBox 绑定(bind)到通用字典

c# - 使用正则表达式替换而不是字符串替换

c# - 为什么这个 AJAX 调用返回整个页面内容?

c# - NSTextField 下拉列表中显示建议