Click here to Skip to main content
15,075,305 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:

I have a question about ICommand and MVVM in WPF.

I have seen that the most common way to handle events is by using interface ICommand.

I understand that if I want to add a command to a button, I do something like this:
<Button Command="{MyCommand}" />

But I don't understand how to create a command to selectionchanged or something for a ListView?

Does anyone know any good examples out there, or could help me with some simple code?


HI Again,
I have still problems with Icommand implementation of SelectionChanged at listView.
I found this post:[^] but I'm not sure what he meean by: "MyCommand can be a DelegateCommand from CAG." How could a CAG class look like?
Updated 14-Apr-11 21:42pm
Dalek Dave 8-Apr-11 3:41am
Edited for Grammar and Spelling, but a nicely phrased question.

First of all, ICommand is not the mechanism to support events. It is the mechanism by which you should perform command based functionality in WPF or Silverlight. The reason I say this is because it goes beyond what an event should do - with commanding infrastructure, you can also affect the UI by determining whether or not something can happen because the ICommand interface also supports a CanExecute method. When something supports ICommand, the UI will actually take this method into account, so that you can't press a button when CanExecute returns false.

As you are now aware, you can't bind an ICommand to a selection changed because it doesn't support command binding. At first, this would seem to be a real problem, but there are a number of solutions that support this. Probably the best implementation is the EventToCommand support in MVVM Light which you can find here[^].

Laurent demonstrates using this behavior here[^].
The best examples I have come across use Attached Properties. A good example of this can be found on Claus Conrads Blog WPF ListView MVVM and missing ICommand[^]. Attached properties can be used for all sorts of things and are definitely worth getting comfortable with.

Hope this helps

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900