Call Command from Code Behind

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 realize this requires a little bit of code behind, but I can't quite figure out what's needed. The command is located in the ViewModel, which is set as the datacontext of the view, but I'm not sure exactly how to route this so I can call it from the code behind of the loaded event. Basically what I want is something like this...

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    //Call command from viewmodel
}

Looking around I can't seem to find the syntax for this anywhere. Do I need to bind the command in the xaml first to be able to reference it? I notice the command bindings option within a user control will not let you bind commands as you can within something like a button...

<UserControl.CommandBindings>
    <CommandBinding Command="{Binding MyCommand}" /> <!-- Throws compile error -->
</UserControl.CommandBindings>

I'm sure there's a simple way to do this, but I can't for the life of me figure it out.


Well, if the DataContext is already set you could cast it and call the command:

var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(null))
    viewModel.MyCommand.Execute(null);

(Change parameter as needed)


Preface: Without knowing more about your requirements, it seems like a code smell to execute a command from code-behind upon loading. There has to be a better way, MVVM-wise.

But, if you really need to do it in code behind, something like this would probably work (note: I cannot test this at the moment):

private void UserControl_Loaded(object sender, RoutedEventArgs e)     
{
    // Get the viewmodel from the DataContext
    MyViewModel vm = this.DataContext as MyViewModel;

    //Call command from viewmodel     
    if ((vm != null) && (vm.MyCommand.CanExecute(null)))
        vm.MyCommand.Execute(null);
} 

Again - try to find a better way...