在 ReactiveUI Windows 表单中将 EventArgs 传递给 ReactiveCommand

Passing EventArgs to ReactiveCommand in ReactiveUI Windows Forms

我将 ReactiveUI 与 Windows Forms 和 c# 一起使用。我不确定如何从 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?

您可以直接处理事件并将其传递给命令。例如,使用标准 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>