c# - Simple explanation of how to use commands with a button click in WPF -


i'm starter , i'm trying use commands instead of click="display".

<button content ="click me!" command = "{binding clickmecommand}" /> 

how write method use command? want display message "clicked!" in console when button clicked. i'm looking simplest implementation easy understand please. i've tried looking @ tutorials on complicate things , hard me understand.

one way this: create viewmodel :

public class mainviewmodel {     public mainviewmodel()     {      }      private icommand clickmecommand;     public icommand clickmecommand     {                 {             if (clickmecommand == null)                 clickmecommand = new relaycommand(i => this.clickme(), null);             return clickmecommand;         }     }      private void clickme()     {         messagebox.show("you clicked me");     } }     

or initialize in constructor.

first paramater of command method executed when click button binded command to. second parameter method enables/disables button based on logic. if button enabled @ times set:

in mainwindow code behind set mainviewmodel datacontext of mainwindow.

public partial class mainwindow : window {     public mainwindow()     {         mainviewmodel vm = new mainviewmodel();         initializecomponent();         this.datacontext = vm;     } } 

and relaycommand class(this implementation of icommand interface). can use other implementation of icommand if want.

public class relaycommand : icommand {     readonly action<object> execute;     readonly predicate<object> canexecute;      public relaycommand(action<object> executedelegate, predicate<object> canexecutedelegate)     {         execute = executedelegate;         canexecute = canexecutedelegate;     }      bool icommand.canexecute(object parameter)     {         return canexecute == null ? true : canexecute(parameter);     }      event eventhandler icommand.canexecutechanged     {         add { commandmanager.requerysuggested += value; }         remove { commandmanager.requerysuggested -= value; }     }      void icommand.execute(object parameter)     {         execute(parameter);     } } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -