我可以在命令中调用命令吗? [英] Can I call a command inside a command?

查看:110
本文介绍了我可以在命令中调用命令吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个closecommand在我的viewmodel中定义我的对话框窗口。我有另一个命令定义里面的viewmodel。现在我有那个命令绑定到我的视图中的控件。执行某些命令操作后,我希望它调用closecommand关闭窗口。这是可能吗?

I have a closecommand defined inside my viewmodel for my dialog window. I have another command defined inside that viewmodel. Now I have that command binded to a control in my view. After performing certain command actions, I want it to call closecommand to close the window. Is that possible?

推荐答案

是的。您可以使用包装两个(或任意数量)其他命令的CompositeCommand。我相信这是在Prism,但如果你没有访问到你的项目,这是不是很难实现类似的功能,你自己,特别是如果你不使用参数 - 你所做的就是实现ICommand然后在类中有一个私有的ICommands列表。

Yes. You can use a CompositeCommand that wraps both (or any number) of your other commands. I believe this is in Prism, but if you don't have access to that in your project, it isn't terribly difficult to implement similar functionality on your own, especially if you're not using parameters - all you do is implement ICommand with a class and then have a private List of ICommands inside the class.

下面是更多关于Prism的CompositeCommand类:

Here's more on the CompositeCommand class from Prism:

http:// msdn .microsoft.com / en-us / library / microsoft.practices.composite.presentation.commands.compositecommand_members.aspx

我自己承认短, - 规范实现如下。要使用它,所有你需要做的是让你的VM上引用,然后绑定到它。您可以为要运行的所有其他命令调用.AddCommand。可能Prism一个实现不同,但我相信这将工作:

My own admittedly short and possibly non-canonical implementation follows. To use it, all you need to do is have this be referenced on your VM, and then bind to it instead. You can call .AddCommand for all the other commands that you want to run. Probably the Prism one is implemented differently, but I believe this will work:

    public class CompositeCommand : ICommand {

    private List<ICommand> subCommands;

    public CompositeCommand()
    {
        subCommands = new List<ICommand>();
    }

    public bool CanExecute(object parameter)
    {
        foreach (ICommand command in subCommands)
        {
            if (!command.CanExecute(parameter))
            {
                return false;
            }
        }

        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        foreach (ICommand command in subCommands)
        {
            command.Execute(parameter);
        }
    }

    public void AddCommand(ICommand command)
    {
        if (command == null)
            throw new ArgumentNullException("Yadayada, command is null. Don't pass null commands.");

        subCommands.Add(command);
    }
}

这篇关于我可以在命令中调用命令吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆