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

    Published by on August 13th, 2009 1:57 pm under Attached Behaviors, Composite Application Guidance for WPF & SL, p&p, Patterns & Practices, Prism-v2, Silverlight, Windows Presentation Foundation, WPF

    18 Comments

    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 :) .

    kick it on DotNetKicks.com

    Shout it

    Tags: , , , , , , ,

    • Mark Cooper

      Hi Damien,

      I have implemented this for a TextChanged event, but noticed that the command fires before the bound Text property makes it back to the ViewModel – so I’m fetching the ‘previous’ value rather than the new one?

      Can you think of any better ways to implement this?

      Thanks,
      Mark

    • Damian Schenkelman

      Hi Mark,

      A possible way to get the current text after it has been modified is the following.
      Make the command parameter of type TextChangedEventArgs and assign it the behavior, like this:
      private void OnTextChanged(object sender, TextChangedEventArgs e)
      {
      CommandParameter = e;
      ExecuteCommand();
      }

      Your delegate command signature should be something like:
      public DelegateCommand TextChanged { get; set; }

      And your Execute method must received TextChangedEventArgs:
      private void OnTextChanged(TextChangedEventArgs args)
      {
      //your code here
      }

      This will allow you to get the latest edited text when your command is executed.

      I hope this was useful for you!

    • Eric Middelkoop

      Hi Damian,

      Could you post a working TextChanged example for TextBoxes in WPF? I am relatively new to WPF and Composite Application Guidance and are struggling with this. I tried to implement the command but the eventhandler is not fired and I can’t find out why.

      Best regards,
      Eric

    • Damian Schenkelman

      Hi Eric,
      I have created a small sample that is based on the commanding quickstart. There is a Textbox which executes a command every time the text changes. The command shows the current text in a message box (really straightforward, but of course not a best practice :) )
      You can download it from here:
      http://cid-09f63fc7ac065e5e.skydrive.live.com/self.aspx/p|0p%20Samples/TextChanged%20Command.zip

      I hope you can find it useful,
      Damian

    • Francisco

      Hello Damian,

      i’m sorry but i cannot seem to find CommandBehaviorBase on the Microsoft.Practices.Composite.Presentation.Silverlight assembly

      Which release of CAL do you refer ?

      Francisco

    • Damian Schenkelman

      Hi Francisco,

      I answered your question in this thread @Codeplex:
      http://compositewpf.codeplex.com/Thread/View.aspx?ThreadId=68510

      I hope you find the answer useful,
      Damian

    • Tishon

      Thanks Damien,

      Very helpful snippet!

    • waday

      Thanks Damien! Works well for combo boxes too!

    • RK

      Hi Damian,

      I have the same issue as Mark. I get the previous value and not the new value.

      I have implemented the changes as suggested by you (after Mark’s comment) can you please suggest how we can get new value?

      Mark,
      Do you get the new value?

    • Damian Schenkelman

      Hi RK,

      The TextBox TextChanged sample is actually the one I used to create the snippet, so it is one that I have tested.

      The approach I mentioned to Mark should work. You could try debugging your application to check when the Text Change event is being fired in the method that is subscribed to it in the created behavior.

      Thanks,
      Damian

    • RK

      Hi Damian,

      I have tried debugging it but it gets the older value only and not the modified value.

      PS: I am using it in Silverlight 3 app (MVVM pattern). Actually i am trying to create list with text box and need text_changed handler to get the sum of all textbox values. (Item panel, itemsource=list, datatemplate = textbox)

      I don’t see any other difference compared to your code. Will silverlight 3 make a difference.

    • Ramkumar

      Hi Damian,
      I have used the demo you provided on the TextChanged event. It works well for the WPF client. However I am using Silverlight 3 in MVVM pattern where my view is having these text box and i want to acheive the similar functionality. But the textchanged command on silverlight does not have enough properties to get the TectChangedEventArgs in my view model.

      The reason i found was that i am using default SL System.Windows.Control, where as your code was using PresentationFramework’s System.Windows.Control.

      Do you know if we can get the same functionality in SL MVVM using prism?

      Thanks in advance

Archives

Categories