WPF command Introduction, command, and data binding integration application

Source: Internet
Author: User

To get started with commands, you must do three things:

One: Define a command

Two: Define the implementation of the command

Three: Create a trigger for the command

The basis of the command system in WPF is a relatively simple ICommand interface with the following code:


{event EventHandler canexecutechanged; bool CanExecute (object parameter); void Execute (object parameter);}

The CanExecute is used to determine whether the command is in an executable state. Typically, UI controls can use CanExecute to enable or disable themselves. That is, when the associated command returns false from CanExecute, the button becomes unavailable.

Execute is the key to the command, and when invoked, it triggers the execution of the command.

To define a new command, you can implement the ICommand interface. If you want ICommand to close the application after it is called, the code is as follows:

public class Exit:icommand {event EventHandler canexecutechanged, public bool CanExecute (object parameter) {return Tru E } public void Execute (object parameter) {Application.Current.Shutdown ();}}
To bind a menu item to the application close this command, you can attach their command property to the Exit command, with the following code:
<menuitem header= "_file" > <menuitem header= "_exit" > <MenuItem.Command> <local:Exit/> </ Menuitem.command> </MenuItem> </MenuItem>
Because it is common to use commands for multiple locations, it is also common to create a static field that stores commands:
public static readonly ICommand Exitcommand = new Exit ();
The advantage of this is that by using this type of ICommand field, you can make the exit command fully privatized. Now, you can mark exit as a private class and convert the tag to a static field with the following code:
<menuitem header= "_file" >            <menuitem header= "_exit" command= "{x:static Local:WinCommand.ExitCommand}"/ >        </MenuItem>
Below we can write a template for the window to implement the function of closing the window by adding a button that is hooked up with the close command, with the following code:
 <Window.Style> <style targettype= "window" > <setter property= "Template" > <Setter.Value> <controltemplate targettype= "window" > <doc kpanel> <statusbar dockpanel.dock= "Bottom" > <statusb Aritem> <button command= "{x:static Applicationcommand S.close} ">Close</Button> </StatusBarItem> </st                    Atusbar> <ContentPresenter/> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> < /window.style> 
We'll then close the window by adding a command binding to the window.
<summary>//    Wincommand.xaml Interactive logic///    </summary> public    partial class Wincommand:window    {public        static readonly ICommand Exitcommand = new Exit ();        Public Wincommand ()        {            InitializeComponent ();            Commandbindings.add (                new commandbinding (                    applicationcommands.close,                    closeexecuted));        }        void Closeexecuted (object sender, Executedroutedeventargs e)        {this            . Close ();        }          }

Use commands to clearly separate the display from the behavior. By using a single name for the desired semantic action signature, many of the resulting tight coupling problems can be avoided when trying to hook up multiple controls and a single event-handling process. In general, application logic should always be implemented by means of a command, not an event handler. For many common examples that need to be directly attached to the event-handling process, it is better to handle them with triggers.

Command and data binding

One of the exciting and powerful features of using commands is integration with data binding. Because both command and CommandParameter are attributes on an element, they can be set to some data that is bound to them. Therefore, you can use the data content of the binding to determine what action should occur.

To demonstrate how they are fused together, the application begins with the file below C: \. First, define a listbox that displays the content, and a data template that shows each file name, with the following code:

<ListBox Margin= "2" Name= "Lbfile">

<listbox.itemtemplate>

<DataTemplate>

<TextBlock Text= "{Binding path=name}"/>

</DataTemplate>

</listbox.itemtemplate>

</ListBox>

In the background, set the Itemsource property to the file list:

Public wincommandandbinding () {InitializeComponent (); fileinfo[] fileList = new DirectoryInfo ("c:\\"). GetFiles ("* *"); Lbfile.itemssource = fileList; }

Now, add a button to display the file, but do not want any files to be opened. So, to provide some kind of filter on the loaded file. Now implement two commands open and blocked and provide them with some kind of processing, the code is as follows:
public static readonly RoutedCommand Opencommand = new RoutedCommand ("Open", typeof (Wincommandandbinding)); public static readonly RoutedCommand Blockedcommand = new RoutedCommand ("Blocked", typeof (Wincommandandbin        Ding));            Public wincommandandbinding () {InitializeComponent ();                    Commandbindings.add (New commandbinding (Opencommand, Delegate (Object Sender,executedroutedeventargs e) {            Process.Start ("Notepad.exe", (string) e.parameter);}));                Commandbindings.add (New commandbinding (Blockedcommand, Delegate (object sender, Executedroutedeventargs e)                {MessageBox.Show (String) e.parameter, "Blocked");            })); fileinfo[] fileList = new DirectoryInfo ("c:\\").            GetFiles ("* *");        Lbfile.itemssource = fileList; }    }
After you have defined two commands, you can update the file's data template to include the button. Use data binding in the command parameter (file name). The corresponding command itself, because you want some entries with Opencommand, and other entries with Blockedcommand, so will use Ivalueconvert to convert the file name to ICommand, the code is as follows:
 <listbox margin= "2" name= "Lbfile" > <ListBox.ItemTemplate> <DataTemplate>                        <WrapPanel> <textblock text= "{Binding path=name}"/> <button margin= "5" commandparameter= "{Binding path=fullname}" > <button.command&                                Gt <Binding> <Binding.Converter> <lo                                Cal:filetocommandconverter/> </Binding.Converter>                    </Binding> </Button.Command> Show </Button> </WrapPanel> </DataTemplate> </ListBox.ItemTemplate> </l Istbox> 
The following is the converter:
public class Filetocommandconverter:ivalueconverter    {Public        object Convert (object value, Type TargetType, Object Parameter,cultureinfo Culture)        {            string ext = ((FileInfo) value). Extension.tolowerinvariant ();            if (ext = = ". txt")                return wincommandandbinding.opencommand;            else                return wincommandandbinding.blockedcommand;        }        public object Convertback (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) c10/>{            throw new NotImplementedException ();        }    }
Operation Result:

This example is a bit trivial, but you can use the CanExecute method to easily perform similar behavior and disable this command for "bad" files. However, the most important point here is that you can return any command. You can use any data-based logic to determine the behavior of any element.

In addition, we can consider whether it is possible to use data triggers to implement it? Oh, you can, this is tantamount to the command, data binding and trigger three to merge together? is not very strong, huh? Here is the code:

 <listbox margin= "2" name= "LbFile2" > <ListBox.ItemTemplate> <DataTemplate>                        <WrapPanel> <textblock text= "{Binding path=name}"/> <button x:name= "Btnshow" margin= "5" commandparameter= "{Binding path=fullname}" Comm                    And= "{x:static Local:WinCommandAndBinding.BlockedCommand}" content= "Block"/> </WrapPanel> <DataTemplate.Triggers> <datatrigger Valu E= ". txt" > <DataTrigger.Binding> <binding path= ' Exte Nsion ' > <Binding.Converter> <local:t Olowerinvariantconvert/> </Binding.Converter> &         Lt;/binding>                   </DataTrigger.Binding> <setter targetname= "Btnshow" Property= "Command" value= "{x:static Local:WinCommandAndBinding.OpenCommand}"/&G                            T                    <setter targetname= "Btnshow" property= "Content" value= "Show"/> </DataTrigger>        </DataTemplate.Triggers> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Converter:
    Class Tolowerinvariantconvert:ivalueconverter    {        object Convert (string)  Object Convertback (new NotImplementedException ();}}    

WPF command Introduction, command, and data binding integration application

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.