C# Code Snippet to Create Commands with Attached Behaviors using Prism

One of the most common questions we get at the Prism forums is of the type: "How do I execute my command when X happens?" (X not being a button being clicked :) ).  A sample of this type of question can be seen here, where a particular command needs to be executed whenever a textbox's text changes. Our answer usually is that the user can create a command with an attached behavior. However, users are not always happy with this answer because of the complexity of having to create an attached behavior to hook up the command

For this reason, with the help of Matias Bonaventura, and Diego Poza's Snippet Creator tool and this group of MSDN sites we created a code snippet that will enable developers to easily create this commands with attached behaviors.
Command Attached Behavior snippet

Pre-Requirements

  1. Download the Snippet Visual Studio installer and run the installer (the snippet is provided "AS IS" with no warranties and confers no rights).
  2. The class where you run the snippet must have the following using statements:
    • The namespace of the Control that has the event your command will attach to.
    • Microsoft.Practices.Composite.Presentation.Commands. The snippet uses the CommandBehaviorBase<T> class of Prism-v2. MSDN site here.
    • System.Windows: For DependencyProperty class for example.
    • System.Windows.Input: Has the ICommand interface.

Using the snippet

Once you have performed the previous steps, you must take into account the following considerations:

  • The snippet will create two classes. You will probably want to put the code it generates in a separate class file, dedicated to that particular command.
  • The shortcut to insert the code snippet is: cmdbehavior. You must press TAB as any other code snippet requires to be inserted in your code.
  • You must fill four replacements (the rectangles in green):
    1. CommandAction: A description of what the behavior handles. Example: TextChanged.
    2. BehaviorNameCommandBehavior: Replace with the name of the command behavior. Example: TextBoxTextChangedCommandBehavior.
    3. ControlType: The type of the control that has the events your command will attach to. Example: TextBox.
    4. EventName: The event of your control you will attach to.
  • To bind the command in XAML, you simply need to add a definition to the namespace and then bind the command property of the $CommandAction$ class to the command in your ViewModel. Example:
    <Window x:Class="WpfApplication1.Window1"
        ...
        xmlns:cmd="clr-namespace:Commanding.Modules.Order.Views">
        <Grid>
            <TextBox cmd:TextChanged.Command="{Binding Path=TextChangedCommand}"></TextBox>
        </Grid>
    </Window>

I hope this snippet is useful for you, and that you are able to save time and problems using it. I know I am :) .