Can I call a command inside a command?

北慕城南 提交于 2019-12-10 22:03:40

问题


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?


回答1:


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.

Here's more on the CompositeCommand class from Prism:

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

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


来源:https://stackoverflow.com/questions/6601270/can-i-call-a-command-inside-a-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!