开发者

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?


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);


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);


MVVM light toolkit => EventToCommand :)

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜