wpf 在不使用mvvmlight的情况下将事件对象和发送者传递给命令

soat7uwm  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(71)

问候语,类似于13年前提出的this问题,我想将sender和eventargs都传递给command,但不向项目添加额外的包(长话短说,那是因为1:它是一个纯ui操作系统,没有view-model或model; 2:我必须使用命令,因为事件是在模板内的ui元素上)。到目前为止,我一直在使用行为框架的PassEventArgsToCommand参数,这已经足够了,但是现在我也需要sender,那么,我如何手动将sender和eventargs传递给命令?一些见解,以防有人发现它对回答这个问题有用:在我的例子中,它是TabControl的头模板,MouseMove事件,我想知道鼠标信息和与此头相关的Visual元素,所以我可以把这个可视元素从TabControl的项目中分离出来,把它放在单独的新创建的控件中,并启动拖放。

sqougxex

sqougxex1#

按照@styx的建议-我已经实现了自定义TriggerAction,绝对不是最通用的解决方案(例如,与WebkeCommandAction代码相比),但对我来说很有效,我猜。还尝试用2个参数实现命令,其中第二个参数是协变的,类型为EventArgs,但记得我受到ICommand接口的Execute(对象)方法的限制,所以必须将参数打包到元组中。下面是我自定义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);
        }
    }
}

字符串

相关问题