Super simple: How to Use WPF commands to improve your code Quality

Source: Internet
Author: User

Code:/files/zhuqil/wpfcommands.zip

Introduction:

WPF commands is a good way to reuse functions in applications. In the example provided in this article, an example of using the WPF command mode to sort the customer is created. The wpfcommand mode is ideal for calling the same function with different controls in an application. WPFcommandS can also be used in some other situations. For example, if the input is incorrect, disable the control. In the canexecute section of the article, we can learn more.

Create a command:

To use WPFcommandS, you must declare a static command. When you declare this command, you can also make sure that "input gestures" can also call this command. You can think of "input gestures" as a shortcut. Some basic keys or even key combinations. For example, in the example project, I use the F3 key as "input gesture ".

Code

/// <Summary>
/// Command to sort the MERs
/// As ou can see the command also hooks to the F3 key of the keyboard
/// </Summary>
Public static routeduicommand sortcustomers = new routeduicommand ("sortcustomers ",
"Sortcustomers", typeof (commandsdemo), new inputgesturecollection (
New inputgesture [] {New keygesture (key. F3, modifierkeys. None, "Sort customer ")}
));

In this example project (Commanddemo. CS. In real-life projects, we recommend that you declare command in a more important place so that Windows/components can use the same command declaration. For example, if another form in the project can also use the MERs sorting function, I will create a class with command in it. In this way, this command can be easily accessed by other forms. You can think of commands as something similar to an event. If someone executes this command, someone will process it. Imagine such a picture in my mind...

There are three guys Jon, Mark and Patrick who works in the store. The store manager decided to ask Patrick to wash the floor. Jon said "wash the floor", and Patrick went to execute it. Mark said, "wash the floor", and Patrick will proceed. Therefore, basically, Patrick is a command Processor, Jon, Mark Execute CommandIt causes Patrick (command processor) to perform this operation. The manager said Patrick is going to wash the floor. Command binding.

The above is a basic explanation of how this mode works. This may be even more confusing. In this way, we will soon forget... In the WPF class, routedcommand is similarRoutedevents. The caller executes this command, and the WPF visual tree directs the route until commandbinding processes this command. During command processing, set E. Handled = true to stop it. 

Now let's continue. After defining this command, what you have to do is how to bind this command. Basically, this means you need to specify who will perform the operation. As follows:

Code

// Here we create handle the command binding for the whole window
// So which ever control invokes this command the same handler will handle the command
Commandbindings. Add (New commandbinding (sortcustomers, sortcustomershandler ));

// Command binding for the delet customer
Commandbindings. Add (New commandbinding (deletecustomer, deletecustomerhandler, canexecutedeletecustomer ));

// Handle the canexecutechange to set the text of the delete text block
Deletecustomer. canexecutechanged + = delegate
{
Bool canexecute = avaloncommandshelper. canexecutecommandsource (deletebutton );
Deletetext. Text = canexecute?
"Delete selected customer ":
"Select customer to delete ";
};

}

// Handler for the sort MERs command.
// This event handler will be invoked when some element will execute the sortcustomers command
Private void sortcustomershandler (Object sender, executedroutedeventargs E)
{
// Default the sort if no parameter is passed
String sortby = E. Parameter = NULL?
"Name ":
E. Parameter. tostring ();

// Get the view for the list
Icollectionview view = collectionviewsource. getdefaultview (customerlist. itemssource );
View. sortdescriptions. Clear ();
// Add the new sort description
View. sortdescriptions. Add (
New sortdescription (sortby, listsortdirection. ascending ));
View. Refresh ();
}

What we need to do is create mark and Jon. They actually execute this command. Some controls are like buttons. When this is clicked, there is a command attribute that lets you determine which command will be used (you even pass a parameter to this command by using the commandparameter attribute ).

> Command = "local: commandsdemo. sortcustomers"

You can run the following C # code manually:

Icommand command = sortcustomers;
Command. Execute ("name ");

Part 2 canexecute:

WPF command has another cool feature:Canexecute. Basically, this is a method that allows you to check whether the command can be executed or not. If you have a command that can only be executed under certain conditions, this is a very convenient function. For example, you have a user list in The ListBox list. To delete a user, you need to define the user ID as the parameter command. You can determine whether to delete a user by obtaining the selected items in ListBox. Pass the ID as the command parameter. Only commands that you can execute when you select.

In canexecutechanged event processing, you must call the canexecute method of the icommand interface to check the current status of the command.

Code

// Handler for the can execute chack of the delete customer
Private void canexecutedeletecustomer (Object sender, canexecuteroutedeventargs E)
{
E. canexecute = E. Parameter! = NULL & E. parameter is customer ;;
E. Handled = true;
}

If canexecute is false, by disabling the control, all controls support the canexecute result in command mode (for example, button. If the command execution control does not support the command mode, do not worry, because it can be executed only when canexecute = true. Of course, there are also (for example, changing the visibility of the control or changing the text attribute of the control ). You can also execute this.

Bool canexecute = command. canexecute (paramterforcommand );

 

I created a help method that accepts an icommandsource and returns the canexecute status of the command.

Code

/// <Summary>
/// Gets the can execute of a specific command
/// </Summary>
/// <Param name = "commandsource"> the command to verify </param>
/// <Returns> </returns>
Public static bool canexecutecommandsource (icommandsource commandsource)
{
Icommand basecommand = commandsource. Command;
If (basecommand = NULL)
Return false;


Object commandparameter = commandsource. commandparameter;
Iinputelement commandtarget = commandsource. commandtarget;
Routedcommand command = basecommand as routedcommand;
If (command = NULL)
Return basecommand. canexecute (commandparameter );
If (commandtarget = NULL)
Commandtarget = commandsource as iinputelement;
Return command. canexecute (commandparameter, commandtarget );
}

As shown in the demo, you can use this method to verify the command status. I hope this article will help you better understand how command works, how to use it to make your application code better. To better use the WPF command mode, you can download the example in this article.

Reference Original:Http://www.codeproject.com/KB/WPF/wpfcommands.aspx

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.