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.
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)