Call Command from Code Behind

前端 未结 6 1136
轻奢々
轻奢々 2020-12-23 19:03

So I\'ve been searching around and cannot find out exactly how to do this. I\'m creating a user control using MVVM and would like to run a command on the \'Loaded\' event.

6条回答
  •  悲哀的现实
    2020-12-23 19:21

    I have a more compact solution that I want to share. Because I often execute commands in my ViewModels, I got tired of writing the same if statement. So I wrote an extension for ICommand interface.

    using System.Windows.Input;
    
    namespace SharedViewModels.Helpers
    {
        public static class ICommandHelper
        {
            public static bool CheckBeginExecute(this ICommand command)
            {
                return CheckBeginExecuteCommand(command);
            }
    
            public static bool CheckBeginExecuteCommand(ICommand command)
            {
                var canExecute = false;
                lock (command)
                {
                    canExecute = command.CanExecute(null);
                    if (canExecute)
                    {
                        command.Execute(null);
                    }
                }
    
                return canExecute;
            }
        }
    }
    

    And this is how you would execute command in code:

    ((MyViewModel)DataContext).MyCommand.CheckBeginExecute();
    

    I hope this will speed up your development just a tiny bit more. :)

    P.S. Don't forget to include the ICommandHelper's namespace too. (In my case it is SharedViewModels.Helpers)

提交回复
热议问题