<Button Content="Paste" Click="Call_ViewModel_Paste" />
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction MethodName="Paste" TargetObject="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Both approaches are correct, they follow MVVM priciples and works without ICommand, but as you can see, neither is as elegant as ICommand
Wouldn't it be enough to provide public methods and bind the action from the view directly to this public method?
How would you for example call a public method when a Button
in the view is clicked?
The answer is that you bind the Command
property of the Button
to an ICommand
property of the view model that calls the method for you. That's the main reason why any actions that view model defines are exposed using commands.
A command is nothing but an object that implements the System.Windows.Input.ICommand
interface and encapsulates the code for the action to be performed.
Please refer to the following links for more information about the concept.
https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
https://msdn.microsoft.com/en-us/magazine/dn237302.aspx
–
–
–
In MVVM you try to avoid "code behind" (this is code in the MyView.cs file) to avoid a tight coupling of View, ViewModel and Model.
In MFC you just registered an event handler (which is still possible in WPF), but in MVVM there is the possibility of just binding a ICommand which will be executed instead of triggering the event.
–
–
Short:
ex. Buttons
Buttons works by creating event (Click="XEvent") that consist of method and then we tell application what to do next i.e. call other methods obviously that works with Code behind. (Event => method is generated at MainWindow.xaml.cs
.)
In MVVM we avoid code behind pattern. to achieve that we need to set the DataContext to other class (will act as middleware) say MainWindowViewModel.cs
.
By implementing ICommand interface and implementing methods to handle the command we avoid code behind maintain MVVM pattern.
Well there can be alternative to ICommand interface like to bind method in ViewModel to command in XAML (Wont prefer though)
<Button Command="{ViewModel AnyMethodName}"/>
ICommand interface will provide you CanExecute method which can be used to enable/Disable controllers simple delegate wont give u that functionality
Hope this helps :)
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.