Commands on objects in a list

Mar 11, 2009 at 6:47 PM
Edited Mar 11, 2009 at 6:52 PM
I was wondering if anyone has had problems with commands being called for the number of elements in a list when a command is defined for that item.  For example, let's say I have 4 buttons in a list and each button has the following:

    Input:CommandService.Command="MyButtonClick"

I have a constructor which calls this for each button I create:

    Buttons.MyButtonClick.Executed += new EventHandler<ExecutedEventArgs>(ButtonClick_Executed);

 

When I click the button ... ButtonClick_Executed gets called for each item in the list ... so, in our example here .. 4 buttons = 4 calls.

Any thoughts?

 

Coordinator
Mar 14, 2009 at 9:11 AM
I think you missunderstood how the command pattern is working. Command is just a static event that can be raise from xaml. It allows a better separation between business logic and UI. When you add Input:CommandService.Command="MyButtonClick" in your xaml, it will attach a behavior to the xaml control raising the executed command when mouse down is pressed. When the it's raised it will notify all its subscribers. So as you said you are attaching an event handler for each button you are notified several times per click. The code to be invoked on command execution should be placed in a class managing your business logic. I often use "Controller" class in my samples to handle this logic (you can see the showcasecontroller in the source). This class is created one time and attaches an handler to the executed event. In your business logic, you can pass additional data by using the Input:CommandService.CommandParameter on you xaml declaration.
Mar 14, 2009 at 8:04 PM
Okay ... that makes sense ... thanks.
Jul 10, 2009 at 5:49 AM

>I often use "Controller" class in my samples to handle this logic (you can see the showcasecontroller in the source).This class is created one time and attaches an handler to the executed event.

You have a singleton controller to prevent the static commands from broadcasting multiple times which is not expected in business logic, but I need viewmodel to handle the commands requested from views because viewmodels have the state of the views and operations to handle the requests. So viewmodel have to subscribe the commands (static events) and in some cases, I have multiple viewmodels of same type instantiated, then would run into the big problem of same command was handled multiple times (as many as viewmodels' instances) - I know this is not the way that commands should be used as they are static events, but indeed I need viewmodels to subscribe their views' commands not a controller to do this

And idea?