Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 287
Kevin DiTraglia Avatar asked Apr 12 '12 15:04

Kevin DiTraglia


1 Answers

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)

like image 55
H.B. Avatar answered Sep 20 '22 17:09

H.B.