tags:

views:

333

answers:

3

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

+2  A: 

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);
Mark Seemann
Thanks Mark, but this doesn't seem to work. I am wanting to invoke the command from the code-behind of the view, which doesn't seem to be able to "see" this command? I would assume this code would work fine if I put it under the ViewModel... but I need something to access behind the view instead.
Mark Pearl
Thanks Mark... I there was a slight adjustment I needed to do to get it working... but you put me on the right track.
Mark Pearl
I see you got it working - good :) It wasn't entirely clear to my from which code-behind file you needed to do this.
Mark Seemann
+1  A: 

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);
Mark Pearl
A: 

MVVM light toolkit => EventToCommand :)

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

msfanboy