Passing eventargs and sender to the command without mvvmlight

83 Views Asked by At

Greeting, similar to this question asked 13 years ago i want to pass both sender and eventargs to command, but without adding an extra package to the project (long story short, that's because 1: it's a purely ui manipulation system, there is no view-model or model; 2: i have to use commands because event is on the ui element inside template). So far i've been using PassEventArgsToCommand parameter from Behaviors framework and it was enough, but now i need sender as well, so, how can i manually pass both sender and eventargs to a command? Some insight in case anyone finds it useful for the purpose of answering the question: in my case it's for TabControl's header template, MouseMove event, where i want to know both mouse info and the Visual element associated with this header, so i can rip this Visual element out of TabControl's items, put it in separate freshly created control and initiate drag-and-drop.

1

There are 1 best solutions below

0
On BEST ANSWER

Following @styx's advise - i've implemented custom TriggerAction, definitely not the most versatile solution (in comparison to InvokeCommandAction code, for example), but works for me, i guess. Also tried to implement command with 2 arguments, where second one is covariant and of type EventArgs, but remembered i'm restricted by Execute(object) method from ICommand interface, so had to pack arguments into tuple. here is my custom TriggerAction:

public sealed class EventToCommandAction : TriggerAction<DependencyObject>
{
    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(EventToCommandAction), null);

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty SenderProperty = DependencyProperty.Register("Sender", typeof(object), typeof(EventToCommandAction), null);
    public object Sender
    {
        get { return GetValue(SenderProperty); }
        set { SetValue(SenderProperty, value); }
    }

    protected override void Invoke(object parameter)
    {
        if (AssociatedObject == null)
            return;

        ICommand command = Command;
        if (command != null)
        {
            Tuple<object, EventArgs> args = new Tuple<object, EventArgs>(Sender, (EventArgs)parameter);
            if (command.CanExecute(args))
                command.Execute(args);
        }
    }
}