I've been programming a lot in WPF lately but my View and ViewModel are not separate at this point. Well, it's partially. All my bindings concerned to text in text boxes, content for labels, lists in datagrids, ... are done by regular properties with a NotifyPropertyChanged event in them.
All my events for handling button clicks or text changed stuff is done by linking the events. Now, I wanted to start working with commands and found this article: http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute. It has an explanation of how to set up MVVM but I'm confused with the RelayCommand
.
What job does it do? Is it useable for all commands in my form? How do I make the button disable when (a) certain text box(es) are not filled in?
EDIT 1:
A good explanation to "Is it useable for all commands in my form?" is answered here: https://stackoverflow.com/a/22286816/3357699
Here is the code I have so far: https://stackoverflow.com/a/22289358/3357699
Commands are used to separate the semantics and the object that invokes a command from the logic that executes the command i.e. it separates UI component from the logic that needs to be executed on command invocation. So, that you can test business logic separately using test cases and also your UI code is loosely coupled to business logic.
Now, that being said let's pick your questions one by one:
I have added the details above. Hope it clears the usage of commands.
Some controls exposed Command DependencyProperty like Button, MenuItem etc. which have some default event registered to it. For Button it's
Click
event. So, if you bindICommand
declared in ViewModel with Button's Command DP, it will be invoked whenever button is clicked on.For other events, you can bind using
Interactivity triggers
. Refer to the sample here how to use them to bind toICommand
in ViewModel.The link you posted doesn't provide complete implementation of
RelayCommand
. It lacks the overloaded constructor to setCanExecute
predicate which plays a key role in enabling/disabling the UI control to which your command is bind to.Bind TextBoxes with some properties in ViewModel and in
CanExecute
delegate returns false if any of the binded property is null or empty which automatically disabled the control to which command is binded to.Full implementation of
RelayCommand
:The benefit of using relay command is that you can bind commands directly to the ViewModels. By using commands in such a way you avoid writing code in the views codebehind.
When using relay commands, you will have to provide two methods. The first one provides a value whether the command can be executed (e.g. "CanExecuteSave"), while the other one will be responsible for executing the command ("ExecuteSave").