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