将 EventArgs 传递给 ReactiveUI Windows 窗体中的 ReactiveCommand



我正在将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 FileDragDrop 中获取 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>

最新更新