Starting with Prism learn WPF (vi) MVVM (ii) Command?

Source: Internet
Author: User

Original: Learn WPF (vi) MVVM (ii) Command from Prism?

Start learning WPF (i) WPF from Prism?

Learn WPF from Prism (ii) prism?

Learn WPF (iii) prism-region from Prism?

Start learning WPF (iv) Prism-module from Prism?

Starting with Prism learn WPF (v) MVVM (a) ViewModel?

Starting with Prism learn WPF (vi) MVVM (ii) Command?

Start with Prism learn WPF (vii) MVVM (iii) event aggregator Eventaggregator?

Command binding what is the commands?

Let's take a look at the official Microsoft Note:

Commanding is an input mechanism in Windows Presentation Foundation (WPF) which provides input handling at a more semantic Level than device input. Examples of Commands is the Copy, Cut, and Paste operations found on many applications.

Although English catch chickens, but does not prevent us from reading the primary information, the Burning Goose ('? ') ), let's look at Google's translation:

Directives are an input mechanism in Windows Presentation Foundation (WPF) that provides more semantic-level input processing than device input. Examples of commands are the copy , cut , and paste operations found in many applications.

It doesn't seem to work! Or just take the example to see:

MainWindow.xaml

<window x:class= "UsingDelegateCommands.Views.MainWindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/        Presentation "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:prism=" http://prismlibrary.com/"    Prism:viewmodellocator.autowireviewmodel= "True" title= "Using delegatecommand" width= "height=" "275" > <stackpanel horizontalalignment= "center" verticalalignment= "Center" > <checkbox ischecked= "{Binding Isena bled} "content=" Can Execute Command "margin="/> <button command= "{Binding Executedelegatecommand}" Content = "Delegatecommand" margin= "ten"/> <button command= "{Binding delegatecommandobservesproperty}" Content= "Delegat Ecommand observesproperty "margin=" "/> <button command=" {Binding delegatecommandobservescanexecute} "Conten t= "Delegatecommand observescanexecute" margin= "ten"/> <button command= "{Binding Executegenericdelegatecommand} "Commandparameter=" PassedParameter "content=" Delegatecommand Generic "margin=" ten "/> <textblock text=" {Binding updatetext} "margin=" 10 " Fontsize= "/> </StackPanel></Window>"

MainWindowViewModel.cs

Using system;using prism.commands;using prism.mvvm;namespace usingdelegatecommands.viewmodels{public class        mainwindowviewmodel:bindablebase {private bool _isenabled;            public bool IsEnabled {get {return _isenabled;}                set {SetProperty (ref _isenabled, value);            Executedelegatecommand.raisecanexecutechanged ();        }} private string _updatetext;            public string UpdateText {get {return _updatetext;}        set {SetProperty (ref _updatetext, value);}        Public Delegatecommand Executedelegatecommand {get; private set;}        Public delegatecommand<string> Executegenericdelegatecommand {get; private set;}        Public Delegatecommand Delegatecommandobservesproperty {get; private set;}        Public Delegatecommand Delegatecommandobservescanexecute {get; private set;}           Public Mainwindowviewmodel () { Executedelegatecommand = new Delegatecommand (Execute, CanExecute); Delegatecommandobservesproperty = new Delegatecommand (Execute, CanExecute).            Observesproperty (() = isenabled); Delegatecommandobservescanexecute = new Delegatecommand (Execute).            Observescanexecute (() = isenabled); Executegenericdelegatecommand = new Delegatecommand<string> (executegeneric).        Observescanexecute (() = isenabled);        } private void Execute () {UPDATETEXT = $ "Updated: {datetime.now}";        } private void Executegeneric (string parameter) {updatetext = parameter;        } private bool CanExecute () {return isenabled; }    }}

View section:

The header introduces the namespace, specifying the Viewmodelocator mode:

xmlns:prism="http://prismlibrary.com/"prism:ViewModelLocator.AutoWireViewModel="True"

Followed by a:

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">    </StackPanel>

Then inside is a set of controls, a checkbox of four button one TextBlock.

    • CheckBox ischecked= "{Binding isenabled}"

check box tick status is bound to a Boolean attribute.

    • Button command= "{Binding Executedelegatecommand}"

Common Command Bindings

    • Button command= "{Binding Executegenericdelegatecommand}" commandparameter= "Passed Parameter"

command bindings with parameters

    • TextBlock text= "{Binding updatetext}"

Binding the data source for the TextBlock Text property

Tips:

Binding syntax property= "{Binding PropertyPath}", PropertyPath is the VM

When the command is binding, you can also take parameters, using the CommandParameter property, the above commandparameter specifies a string "Passed Parameter", Of course, you can also binding an object to it.

ViewModel section:

In the Set method:

SetProperty(ref _isEnabled, value);

Notification of property changes, which notifies VM changes when the view state is updated _isEnabled .

ExecuteDelegateCommand.RaiseCanExecuteChanged();

This code will notify Executedelegatecommand of the executable state change, and let him regain the executable state, then how did he get the executable state? Let's take a look at this command:

ExecuteDelegateCommand = new DelegateCommand(Execute, CanExecute);

New, there are two parameters, the first is the action (no Return type method) Execute, the second is a Func

private bool CanExecute(){     return IsEnabled;}

Very simple, directly returned IsEnabled , and he is with the view of the checkbox of the ischecked binding, of course, can also return _isEnabled , and I prefer the back of this, public that is for outsiders, clams.

Of course the executable state , there are other more elegant wording:

            DelegateCommandObservesProperty = new DelegateCommand(Execute, CanExecute)                .ObservesProperty(() => IsEnabled);            DelegateCommandObservesCanExecute = new DelegateCommand(Execute)                .ObservesCanExecute(() => IsEnabled);

The following is a command with a parameter, and his callback function requires a string parameter, specifying the type of the entry parameter at NEW:

            ExecuteGenericDelegateCommand = new DelegateCommand<string>(ExecuteGeneric)                .ObservesCanExecute(() => IsEnabled);

callback function Executegeneric:

        private void ExecuteGeneric(string parameter)        {            UpdateText = parameter;        }

Summarize:

Classes that are ViewModel (VMS, also occasional VMS, also referred to as ViewModel) need to inherit bindablebase,bindablebase to implement the INotifyPropertyChanged interface.

The command type is Delegatecommand, which inherits from Delegatecommandbase, and Delegatecommandbase implements the ICommand interface.

These two interfaces are the underlying interfaces of MVVM. Interested can look at mvvmfoundation, he encapsulated not so many times, only four CS file, you can see directly, he is how to use the ICommand and INotifyPropertyChanged interface.

But, as advanced as we are, with a high-grade package, with a match who also has a speculum wood to take fire, 233333

Compound command Binding

Normally, our command callers call our commands directly, but sometimes we need to invoke the command from outside (such as other views or parent views), then we need a compositecommand.

Compositecommand is a command made up of multiple subcommands. It provides the ability to execute all associated methods (execute and canexecute) of subcommands, and Compositecommand can be executed when all subcommands have an executable state of true.

Take a look at the code for the specific application:

Statement:

public CompositeCommand SaveCommand { get; } = new CompositeCommand();

To register a sub-command:

SaveCommand.RegisterCommand(UpdateCommand);

Cancel Registration:

SaveCommand.UnregisterCommand(UpdateCommand);

Starting with Prism learn WPF (vi) MVVM (ii) 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.