Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>RelayCommand</code> uses functions (more precisely, delegates) passed into its constructor to implement <code>CanExecute</code> and <code>Execute</code> methods.</p> <p>In this sample two functions are passed. First describes how to save - just call <code>Save</code> method on <code>RelayCommand</code> owner. Another one describes, how to check if saving is possible - just check current state of owner's <code>CanSave</code> property.</p> <p>In this way you don't have to create your own <code>Command</code> class explicitly.</p> <p>UPD:</p> <blockquote> <p>Thanks, but my questions is Save() is of type Action, defined as Action and as per my understanding Save() should have a parameter in order to work. But some reason it is able to work even without a paramter.</p> </blockquote> <p>Ok, let's look at it closer. </p> <pre><code> _saveCommand = new RelayCommand(param =&gt; this.Save(), param =&gt; this.CanSave ); </code></pre> <p>is equivalent of (in syntax of C# v2.0)</p> <pre><code> _saveCommand = new RelayCommand( new Action&lt;object&gt;(delegate(object param){ this.Save(); }), new Func&lt;object,bool&gt;(delegate(object param){ return this.CanSave; })); </code></pre> <p>So, you create anonymous functions wrap actual methods leaving to you right to use or not to use their own parameters.</p> <p>If you want to go deeper, the code above is compiled under the hood to something like:</p> <pre><code> // it is OK to ignore methods arguments. // So, it's also OK to ignore them in anonymous methods as well private void Save_Anonymous(object parameter){ this.Save(); } private bool CanSave_Anonymous(object parameter){ return this.CanSave; } .... _saveCommand = new RelayCommand(new Action&lt;object&gt;(this.Save_Anonymous), new Func&lt;object, bool&gt;(this.CanSave_Anonymous)); </code></pre> <p>Note that compiler can select other strategies for implementing delegates, depending on what values they enclose from surrounding context. E.g. if your anonymous functions referenced some local variables compiler would generate anonymous class that contained those variables and put methods in this class.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload