Mark Pearl
Mark Pearl

Reputation: 7653

MVVM Pattern - How can I trigger an ICommand or CommandReference in the code behind

I have been looking for this on Stack Overflow, but couldnt find an answer to this yet so I hope this isnt a duplicate...

I have an app using the MVVM pattern, I like to keep things clean, but sometimes a little code behind seems cleaner than the XAML workaround.

I want to know if it is possible to trigger a command from the codebehind.

I have set up a command reference in my view already (see below)

<local:CommandReference 
                 x:Key="CommandReferencePreviewReportsCommand" 
                 Command="{Binding PreviewReportsCommand}" />

What I want to do is be able to trigger the command reference or the ICommand from the c# code behind of the view. Does anyone know how to do this?

Upvotes: 6

Views: 7562

Answers (3)

msfanboy
msfanboy

Reputation: 5291

MVVM light toolkit => EventToCommand :)

http://galasoft.ch/mvvm/resources/Manual/GalaSoft.MvvmLight.Binaries.V3.Alpha3.zip

Upvotes: 1

Mark Pearl
Mark Pearl

Reputation: 7653

Okay... Mark Seemann - You out me on the right track... so I upped your vote...

I didnt realize that the data context could be type cast, which would then make the commands in the ViewModel visible... so the code below works for my situation.. and a generic solution would be similar.

((ViewModel.PrintSelectViewModel) this.DataContext).PreviewReportsCommand.Execute(null);

Upvotes: 4

Mark Seemann
Mark Seemann

Reputation: 233125

You can just invoke the command from the code-behind:

var parameter = null; // can also be any object you'd like to use as a parameter
this.PreviewReportsCommand.Execute(parameter);

Upvotes: 7

Related Questions