Custom WPF command pattern example

Question :

Custom WPF command pattern example,

Answer :

I’ve done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands?


Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does.

You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so:

public static class CommandBank  {    /// Command definition for Closing a window    public static RoutedUICommand CloseWindow { get; private set; }      /// Static private constructor, sets up all application wide commands.    static CommandBank()    {      CloseWindow = new RoutedUICommand();      CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));      // ...    }  

Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above:

/// Closes the window provided as a parameter  public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)  {    ((Window)e.Parameter).Close();  }    /// Allows a Command to execute if the CommandParameter is not a null value  public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)  {    e.CanExecute = e.Parameter != null;    e.Handled = true;  }  

The second method there can even be shared with other Commands without me having to repeat it all over the place.

Read More  Best implementation for Key Value Pair Data Structure?

Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close.

public partial class SimpleWindow : Window  {    private void WindowLoaded(object sender, RoutedEventArgs e)    {      // ...      this.CommandBindings.Add(        new CommandBinding(          CommandBank.CloseWindow,          CommandBank.CloseWindowExecute,          CommandBank.CanExecuteIfParameterIsNotNull));        foreach (CommandBinding binding in this.CommandBindings)      {         RoutedCommand command = (RoutedCommand)binding.Command;         if (command.InputGestures.Count > 0)         {           foreach (InputGesture gesture in command.InputGestures)           {             var iBind = new InputBinding(command, gesture);             iBind.CommandParameter = this;             this.InputBindings.Add(iBind);           }         }      }        // menuItemExit is defined in XAML      menuItemExit.Command = CommandBank.CloseWindow;      menuItemExit.CommandParameter = this;      // ...    }      // ....  }  

I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn’t try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event.

Read More  Why doesn’t inheritance work the way I think it should work?

Let me know if you have any follow up questions. 🙂

That’s the answer Custom WPF command pattern example, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you

Read More  Is there any list datatype in MySQL stored procedures, or a way to emulate them?