3

I'm using ReactiveUI with Windows Forms and c#. I am not sure how to access the EventArgs from within a ReactiveCommand.

My view:

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

ViewModel:

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

How do I get the DragDrop EventArgs from within the ReactiveCommaand FileDragDropped?

Michael C.
  • 93
  • 7

1 Answers1

3

You could just handle the event directly and pass it to the command. For example with a label in standard WPF and using the ReactiveUI.Events nuget package.

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

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

or if you want to stick with XAML then create at attached behavior

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();
    }
}

and use it like

<Label>
    <i:Interaction.Behaviors>
        <c:DropCommand Command="{Binding DropCommand}" />
    </i:Interaction.Behaviors>
</Label>
bradgonesurfing
  • 30,949
  • 17
  • 114
  • 217
  • 1
    i am using Windows Forms (not WPF), but the first block works in Windows Forms too. Thanks! – Michael C. Apr 10 '17 at 21:06
  • Just ignore that XAML part and use the direct event binding. If the answer works for you then you should mark it as accepted. – bradgonesurfing Apr 11 '17 at 12:22
  • 1
    I tried your attached behavior and it didn't work. Turns out I had to add a .Subscribe() after the execute command: `_Disposable = AssociatedObject.Events().Drop.Subscribe(e => { Command?.Execute(e).Subscribe(); Debug.WriteLine("Something is dropped!"); });` – Robert May 01 '20 at 08:11