3 command for "go" to "WPF" MVVM mode

Source: Internet
Author: User

1.DelegateCommand

2.RelayCommand

3.AttachbehaviorCommand

Because the MVVM pattern is suitable for WPF and SL, there are some minor differences in these 3 modes, such as the Commandmanager method below Relaycommand, which is not available under SL, but I think the basic ideas in these 3 methods are the same, It's all from the article of the Foreign Bull man. The main difference is the use of bindings to the controls in the view. A little different attachbehaviorcommand is a kind of design pattern inside PRISM4, this difference is a bit big. But I think the most convenient is still this delegatecommand.

Delegatecommand
    <summary>///Delegatecommand, this wpf.sl can be used, the view is directly using interaction trigger excitation. More reliable, suitable for different UIElement controls//</summary> public class Delegatecommand:icommand {func<object, bool& Gt        CanExecute;        Action<object> executeAction;        BOOL Canexecutecache; Public Delegatecommand (action<object> executeAction, Func<object, bool> canexecute) {THIS.E            Xecuteaction = executeAction;        This.canexecute = CanExecute; } #region ICommand members public bool CanExecute (object parameter) {BOOL temp = CANEXECU            Te (parameter);                if (canexecutecache! = temp) {Canexecutecache = temp;                if (canexecutechanged! = null) {canexecutechanged (this, new EventArgs ());        }} return Canexecutecache;        } public event EventHandler canexecutechanged; Public void Execute (object parameter) {executeAction (parameter); } #endregion}

This class might be able to understand that the action and func,action in the constructor are responsible for determining whether the execution of this command,action is the method to be executed after the command is triggered. This understanding is the most obvious, but to just familiar with the command of me, so that the most convenient memory and learning, in order to use the ICommand interface implementation methods and the interpretation of the event can be found, but at the beginning of understanding is still a bit obscure.

Here is an example of using this command in a VM. Binding a button control, the simplest example. Cm1click is the fuc inside the constructor that is responsible for executing the method that responds to the event. Cancm1click is the action inside the constructor, which is responsible for judging whether the command response event is executed, which is not used in judgment, and directly assigns a true.

public class testviewmodels:inotifypropertychanged{public        testviewmodels ()        {            ...            Cm1click = new Delegatecommand (Cm1click,cancm1click);   Initialize Delegatecommand                    }       ....       Delegatecommand        #region Command1 public        ICommand Cm1click {get; set;}        public void Cm1click (object param)        {            MessageBox.Show ("CM1 clicked!");        }        private bool Cancm1click (object param)        {            return true;        }        #endregion Command1 ...       }

In XAML, it is a good thing to use interaction to bind the event instead of using command to bind it in a button, which is very intuitive and can respond to many other events

<button x:name= "BTN_CM1" content= "Delegatecommand" height= "+" width= "148" >            <i:interaction. triggers>                <i:eventtrigger eventname= "click" >                    <i:invokecommandaction command= "{Binding Cm1click} "/>                </i:EventTrigger>            </i:interaction. Triggers>        </Button>

Relaycommand

Relaycommand was originally a custom command used under WPF, mainly because it used the event management function, which is not in the SL below. But this part of the code, if modified, can also be used under SL, and WPF below the implementation of the idea is similar.

First look at the definition of Relaycommand, a total of 2 kinds.

public class Relaycommand<t>: ICommand {public Relaycommand (action<t> execute): this (E        Xecute, NULL) {} public Relaycommand (action<t> Execute, predicate<t> canexecute)            {if (execute = = null) throw new ArgumentNullException ("execute");            _execute = Execute;        _canexecute = CanExecute; } [DebuggerStepThrough] public bool CanExecute (object parameter) {return _canexecute = = N Ull?        true: _canexecute ((T) parameter);            } public Event EventHandler canexecutechanged {add{} remove{}//add            {//if (_canexecute! = null)//commandmanager.requerysuggested + = value; }//remove//{//if (_canexecute! = null)//Commandmanager.            requerysuggested-= value;    //}        }    public void Execute (object parameter) {_execute ((T) parameter);        } readonly action<t> _execute = null;        readonly predicate<t> _canexecute = null;        BOOL Icommand.canexecute (object parameter) {throw new NotImplementedException ();            } event EventHandler Icommand.canexecutechanged {add {throw new NotImplementedException ();}        Remove {throw new NotImplementedException ();}        } void Icommand.execute (object parameter) {throw new NotImplementedException (); }    }

The first is to use the generic Relaycommand definition

public class Relaycommand:icommand {public Relaycommand (Action execute): This (execute, NULL) {} public Relaycommand (Action Execute, func<bool> canexecute) {if (execute = = N            ull) throw new ArgumentNullException ("execute");            _execute = Execute;        _canexecute = CanExecute; } [DebuggerStepThrough] public bool CanExecute (object parameter) {return _canexecute = = N Ull?        true: _canexecute ();            } public Event EventHandler canexecutechanged {//The implementation is commented out here, so it can be used under SL.        Add {} remove {}//add//{//if (_canexecute! = null)//            commandmanager.requerysuggested + = value; }//remove//{//if (_canexecute! = null)//Commandmanager.reque            rysuggested-= value; }} publicvoid Execute (object parameter) {_execute ();        } readonly Action _execute;    ReadOnly func<bool> _canexecute; }

The second is the most commonly used definition, you can see in the Canexecutechanged event the Commmandmanager method is commented out, you can use this class under SL, and now look like there is no problem.

In the code, Relaycommand and Delegatcommand basically no difference, but also to achieve the Func and action two parameters of the method, the basic idea of the same.

Their biggest difference is in the way the front-end is called. Delegatecommand uses the interaction in the SDK of expression to bind events, which is bound directly through the command property of ButtonBase, so only click events can be performed, so the scope is limited, However, if you use interaction to bind events, the implementation will be the same as Delegatecommand. But in order to summarize the study, or separate to distinguish.

Code for the front-end XAML

<button x:name= "btn_cm2" content= "Command2" height= "103" horizontalalignment= "left" margin= "115,123,0,0" Verticalalignment= "Top" width= "109" command= "{Binding command2}"/>

Background

Private ICommand _command2;        Public ICommand command2        {            get            {                if (This._command2 = = null)                {                    This._command2 = new Relaycommand (                        () = This.cm2click (),                        () = this. Cancm2click);                }                return this._command2;            }            set {}        } public        bool Cancm2click        {            get {return true;}        }        public void Cm2click ()        {            MessageBox.Show ("CM2 clicked!");        }

3 command for "go" to "WPF" MVVM mode

Related Article

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.