Introduction to the WPF Command Framework

Introduction to the WPF Command Framework

indows Presentation Foundation (WPF) not only lets you do new things, it lets you do familiar things in new ways. As we’re all developers, rather than going through the background information, this article just dives right in with an example and works from there. Here’s a simple user interface?a typical window with a ListBox and a menu (see Figure 1).

?
Figure 1. Typical Simple Window: Here’s a simple window example that contains a ListBox and a Delete menu.

In this example, you want to make sure that users have selected a customer from the list before they can click the Delete menu. How many times have you added this sort of code to one of your Windows applications?

   private void HandleMenus()   {      menuDelete.IsEnabled = lsbCustomers.SelectedItem != null;   }

The code disables the Delete menu based on whether a user has selected a Customer. Code such as this is a common approach to keep menus and buttons enabled or disabled at the right times. Usually, calls to this or similar methods are riddled throughout the user interface like this:

   private void lsbCustomers_SelectionChanged(object sender,        SelectionChangedEventArgs e)
?
Figure 2. More Complex Window: Adding a second list box to the window example complicates the UI code for enabling or disabling the Delete menu.
{ HandleMenus(); }

This is a venerable approach, but it can easily become convoluted as your UI becomes more complicated. For example, suppose the window has two list boxes (see Figure 2).

Even though this still isn’t a complicated window, simply adding one more list box requires even more conditional code to properly handle the enabling of the Delete menu.

   private void HandleMenus()   {      menuDelete.IsEnabled =          (lsbCustomers.SelectedItem != null &&          ((ListBoxItem)lsbCustomers.SelectedItem).IsFocused) ||         (lsbProducts.SelectedItem != null &&          ((ListBoxItem)lsbProducts.SelectedItem).IsFocused);                               }

It also requires additional code to determine which ListBox the delete operation should affect.

   private void menuDelete_Click(object sender, RoutedEventArgs e)   {      if (lsbCustomers.SelectedItem != null &&          ((ListBoxItem)lsbCustomers.SelectedItem).IsFocused)            lsbCustomers.Items.Remove(lsbCustomers.SelectedItem);      else if (lsbProducts.SelectedItem != null &&          ((ListBoxItem)lsbProducts.SelectedItem).IsFocused)            lsbProducts.Items.Remove(lsbProducts.SelectedItem);   }

Imagine a window with as few as five controls that support the Delete operation. The code necessary to wire up each one of those quickly becomes burdensome. This burden is exacerbated when more than one control can invoke the Delete operation. Fortunately, WPF provides a better approach. The WPF command framework simplifies the UI code required in situations like these because it separates commands from implementation, letting you bind controls to specific commands, as you’ll see next.

Enter WPF Commands
Here’s how you could hook up the first example (the single list box window) with WPF commands.

                                                                          Grissom       Brass       Sara       Warrick   

Notice that the preceding code assigns a value to the Command property of the Delete menu. It also adds a command binding to the customer ListBox. In this scenario, the Menu is the command source, and the ListBox acts as a command target. The CommandBinding specifies delegates for CanExecute and Executed. Here are their implementations:

   private void DeleteCustomer_CanExecute(      object sender, CanExecuteRoutedEventArgs e)   {      e.CanExecute = lsbCustomers.SelectedItem != null;   }      private void DeleteCustomer_Executed(object sender,       ExecutedRoutedEventArgs e)   {      lsbCustomers.Items.Remove(lsbCustomers.SelectedItem);   }

So far, the code doesn’t look all that different from the first example. However, the benefits of this approach become clearer when you add the second “Products” list box:

                               Widget     Whatsit     Something   

Again, you need only to implement the CanExecute and Executed methods, as shown below:

   private void DeleteProduct_CanExecute(object sender,       CanExecuteRoutedEventArgs e)   {      e.CanExecute = lsbProducts.SelectedItem != null;   }      private void DeleteProduct_Executed(object sender,       ExecutedRoutedEventArgs e)   {      lsbProducts.Items.Remove(lsbProducts.SelectedItem);   }   
Author’s Note: The CanExecute method gets called a lot?make it efficient!

Unlike the traditional approach, when using the WPF command approach, you don’t need to change the command source (the Delete menu) code to add the second list box.

Also note that you don’t have to consider which control has the focus in this implementation. The CommandManager (the class that coordinates WPF commands) interacts with the FocusManager to determine which control currently has the focus.

WPF Command Framework Basics
Keeping that brief example in hand, here’s some basic information about how the WPF command framework works.

Command Sources
A command source, such as a button or menu, invokes commands. Usually, command sources implement ICommandSource. You can also invoke commands declaratively, through InputBindings. With an InputBinding in place, when an InputGesture (such as Ctrl-C for copy) occurs, the framework invokes the associated command (such as, ApplicationCommands.Copy).

Built-In Commands
WPF controls are hooked up to some commands/input gestures out of the box. There are many of these built-in commands in the .NET framework. The first example used the ApplicationCommands.Delete command. Other built-in commands include Copy, Paste, and many more. These commands are made even handier because many of the WPF controls are aware of them. For example, you don’t have to do anything special to wire up Copy and Paste to a TextBox; the TextBox control already has the bindings built in, and automatically implements commands such as Copy and Paste.

No Automatic Implementation
However, WPF commands don’t implement command behavior. This is probably the most common misconception developers have when learning about WPF commands. WPF commands merely notify UI elements that a command has been invoked?the UI elements themselves must implement any desired behavior. This separation of command from behavior is a very powerful feature, as you can see in the preceding example, where the Delete command is invoked via the same source (the Delete menu), but has two completely different implementations.

Also, WPF commands do not automatically provide undo/redo capabilities; if you need those capabilities, you still have to implement them manually within your application. However, you can connect your code to the WPF Undo and Redo commands to cause the corresponding actions to occur.

Differences Between Routed Commands and Windows Events
Routed commands are commands that implement the ICommand interface, and are routed through the WPF element tree. The RoutedCommand class provides an implementation of this behavior. Windows events, on the other hand, are not routed. The traditional approach for responding to user action involves writing code in event handlers (such as Menu_Click). That approach requires the event-handling code to consider which control has the focus, as in the HandleMenus code shown earlier.

One of the advantages of using RoutedCommands is that the framework takes care of managing focus. When using RoutedCommands, you don’t need to write code to consider focus.

Despite their power, WPF Commands don’t solve all of your problems out of the box. For example, when editing formatted text, it is common to show the toggle status of bold, italic, underline, etc., as the user selects text. While this capability doesn’t exist as a first-class citizen in the framework, the community has come up with several approaches to solve the problem of communicating additional status back to menu items.

Custom Commands
Creating your own commands is both very useful and quite easy to do?you can use any class that implements the ICommand interface. However, the framework already includes the RoutedUICommand that implements the ICommand interface nicely, so you can usually use that instead. As an example, here’s how to add a command that represents inserting a customer.

   public static class MyCommands   {      static MyCommands()      {         InsertCustomer = new RoutedUICommand(            "Insert Customer", "InsertCustomer",             typeof(MyCommands));      }         public static RoutedUICommand InsertCustomer       {          get; private set;       }   }

Now add a menu item to the window:

      

Also, add a CommandBinding to the window:

              

And finally, add the implementation code:

      private void InsertCustomer_CanExecute(object sender,       CanExecuteRoutedEventArgs e)   {      e.CanExecute = true;   }      private void InsertCustomer_Executed(object sender,       ExecutedRoutedEventArgs e)   {      ListBoxItem item = new ListBoxItem();      item.Content = "New Customer";      lsbCustomers.Items.Add(item);   }   
Author’s Note: If the CanExecute status of a command changes outside of a change in focus (such as when an asynchronous operation completes), call CommandManager.InvalidateRequerySuggested.

The WPF Command Framework is a simple yet powerful framework that makes connecting menus and buttons to command implementations easy and helps keep your code organized.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1