I’ve just started learning the MVVM Light framework and I can’t find any straightforward examples on how to use a RelayCommand. For purposes of learning, I’d just like to have a button in my view which when clicked show’s a hello world world message box, and which is enabled on every even minute (basically if DateTime.Now.Minute % 2 == 0).
How would the button XAML look and how would the RelayCommand HelloWorld be defined in the ViewModel?
Thanks for your help!!
RelayCommand‘s purpose is to implement theICommandinterface that Button controls needs and to just pass the calls onto some other function which generally sits right next to them in the ViewModel.So for example, you would have a ViewModel class like:
In your control you would have the
DataContextset either in the code behind or in the XAML directly through aDataContext={StaticResource ...}Your button would then bind to the command in the ViewModel like so
When the Button is clicked, it uses the
DisplayMessageCommandand callsExecute()on this object whichRelayCommandjust forwards onto theDisplayMessagemethod.The
DispatchTimergoes off once a minute and callsRaiseCanExecuteChanged(). This allows the button which is bound to the command to re-check if the command is still valid or not. Otherwise, you might click the button only to find out that the command isn’t currently available.