【问题标题】:Passing EventArgs to ReactiveCommand in ReactiveUI Windows Forms在 ReactiveUI Windows 窗体中将 EventArgs 传递给 ReactiveCommand
【发布时间】:2017-04-10 00:14:46
【问题描述】:

我正在使用带有 Windows 窗体和 c# 的 ReactiveUI。我不确定如何从 ReactiveCommand 中访问 EventArgs。

我的看法:

this.BindCommand(ViewModel, vm => vm.FileDragDropped, v => v.listViewFiles, nameof(listViewFiles.DragDrop));

视图模型:

FileDragDropped = ReactiveCommand.Create(() =>
{
    // Do something with DragEventArgs
    // Obtained from listViewFiles.DragDrop in View
});

如何从 ReactiveCommaand FileDragDropped 中获取 DragDrop EventArgs?

【问题讨论】:

标签: c# .net winforms events reactiveui


【解决方案1】:

您可以直接处理事件并将其传递给命令。例如,使用标准 WPF 中的标签并使用 ReactiveUI.Events nuget 包。

var rc = ReactiveCommand.Create<DragEventArgs>
    ( e => Console.WriteLine( e ));

this.Events().Drop.Subscribe( e => rc.Execute( e ) );

或者,如果您想坚持使用 XAML,则在附加行为处创建

public class DropCommand : Behavior<FrameworkElement>
{
    public ReactiveCommand<DragEventArgs,Unit> Command
    {
        get => (ReactiveCommand<DragEventArgs,Unit>)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    // Using a DependencyProperty as the backing store for ReactiveCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ReactiveCommand<DragEventArgs,Unit>), typeof(DropCommand), new PropertyMetadata(null));


    // Using a DependencyProperty as the backing store for ReactiveCommand.  This enables animation, styling, binding, etc...


    private IDisposable _Disposable;


    protected override void OnAttached()
    {
        base.OnAttached();
        _Disposable = AssociatedObject.Events().Drop.Subscribe( e=> Command?.Execute(e));
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        _Disposable.Dispose();
    }
}

并像使用它

<Label>
    <i:Interaction.Behaviors>
        <c:DropCommand Command="{Binding DropCommand}" />
    </i:Interaction.Behaviors>
</Label>

【讨论】:

  • 我使用的是 Windows 窗体(不是 WPF),但第一个块也适用于 Windows 窗体。谢谢!
  • 忽略 XAML 部分并使用直接事件绑定。如果答案对您有用,那么您应该将其标记为已接受。
  • 我尝试了您的附加行为,但没有成功。原来我必须在执行命令之后添加一个 .Subscribe() :_Disposable = AssociatedObject.Events().Drop.Subscribe(e =&gt; { Command?.Execute(e).Subscribe(); Debug.WriteLine("Something is dropped!"); });
猜你喜欢
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多