WPF self-Learning Primer (11) WPF MVVM Mode Command command

Source: Internet
Author: User

The examples in the WPF self-Learning Primer (10) WPF MVVM Simple introduction seem to run without problems or can be updated. But that's not the right way to use MVVM. As I said in the previous article, the goal of MVVM is to minimize the coupling of XAML files and CS files, separating the interface and business logic, so we do not write code in the view background as much as possible. But in this example, we'll write the updated ViewModel code in the view, and in the next example we'll separate the button's event by command.

Because command commands are required in this article, let's start by simply understanding the command commands. The steps to use a command in WPF are simple

1. Create a command

2. Binding commands

3. Set the command source

4. Set the command target

The core of the commands in WPF is the System.Windows.Input.ICommand interface, which is implemented by all command objects. When creating your own commands, you cannot implement the ICommand interface directly, but instead use the System.Windows.Input.RouteCommand class, which already implements the ICommand interface, and all WPF commands are instances of the Routecommand class. Most of the commands that are processed in a program are not RoutedCommand objects, but instances of the Routeduicommand class that inherit from the Routecommand class.

WPF provides a good way to resolve the issue of event binding--icommand. Many controls have command properties, and if not, we can bind the commands to triggers. Next, let's implement a ICommand interface first. ICommand requires a user-defined two method bool CanExecute and void Execute. The first method allows us to determine whether the command can be executed, and the second method is our specific command.

1 usingSystem;2 3 usingSystem.Collections.Generic;4 5 usingSystem.Linq;6 7 usingSystem.Text;8 9 usingSystem.Windows.Input;Ten  One   A  - /*********************** Dusk before dawn ********************************** -  the * After dawn before dusk -  - * CLR version: 4.0.30319.42000 -  + * Creation time: 2018-04-05 22:57:56 -  + * Namespace: Example3 A  at * Unique ID: b9043d4c-fdd7-4e0f-a324-00f0f09286d0 -  - * Machine Name: HLPC -  - * Contact e-mail: [Email protected] -  in * -  to * Description: +  - * the  * * Revision History: $ Panax Notoginseng * -  the * +  A *****************************************************************/ the  + namespaceExample3 -  $ { $  -      Public classRelaycommand:icommand -  the     { - Wuyi         #regionField the  -         ReadOnlyFunc<boolean>_canexecute; Wu  -         ReadOnlyAction _execute; About  $         #endregion -  -   -  A         #regionconstructor function +  the          PublicRelaycommand (Action execute) -  $: This(Execute,NULL) the  the         { the  the         } -  in          PublicRelaycommand (Action Execute, func<boolean>CanExecute) the  the         { About  the             if(Execute = =NULL) the  the                 Throw NewArgumentNullException ("Execute"); +  -_execute =Execute; the Bayi_canexecute =CanExecute; the  the         } -  -         #endregion the  the   the  the         #regionMembers of the ICommand -  the          Public EventEventHandler canexecutechanged the  the         {94  the Add the  the             {98  About   - 101                 if(_canexecute! =NULL)102 103commandmanager.requerysuggested + =value;104  the             }106 107 Remove108 109             { the 111   the 113                 if(_canexecute! =NULL) the  thecommandmanager.requerysuggested-=value; the 117             }118 119         } - 121  122 123 [DebuggerStepThrough]124  the          PublicBoolean canexecute (Object parameter)126 127         { - 129             return_canexecute = =NULL?true: _canexecute (); the 131         } the 133  134 135          Public voidExecute (Object parameter)136 137         {138 139 _execute (); $ 141         }142 143         #endregion144 145     }146 147 }148 149  

We will then declare a ICommand field in our Nameviewmodel:

1 #regionCommand2 3         voidUpdatenameexecute ()4 5         {6 7              This. UserName ="after dawn before dusk";8 9              This. CompanyName ="medium soft easy to pass technology";Ten  One         } A  -   -  the         BOOLCanupdatenameexecute () -  -         { -  +             return true; -  +         } A  at   -  -          PublicICommand UpdateName {Get{return NewRelaycommand (Updatenameexecute, canupdatenameexecute);} } -  -   -  in         #endregion

Finally, we bind the event to this command:

<button content= "Update" command= "{Binding updatename}" margin= "/>"

Run and see the results. We succeeded in separating the events.

Seeing the results above, it seems that we have solved all the problems so far. We see the data being run, the events are bound, and the interface is perfectly separated. When it comes to dealing with problems, it seems that we need to consider commonality, so we can extract the MVVM as a framework to better solve the problem. Next time we'll see how the extraction becomes a universal framework.

The DEMO:WPFMVVMDemo2.zip of this article

Https://pan.baidu.com/s/1xZvsrMbDOXlpvDbCh2Af3Q Password: 6666

WPF self-Learning Primer (11) WPF MVVM Mode Command command

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.