DelegateCommand strange behaviour with custom type

Topics: Prism v2 - WPF 3.5
Apr 10, 2009 at 5:09 PM

I have a module with a Presenter, a View and a Controller


IPresenter Model

Presenter : IPresenter

ICommand AddAnagraficaCommand

Controller : IController

DelegateCommand<AnagraficaEntity> AddAnagraficaCommand = new DelegateCommand <AnagraficaEntity>(OnAddEnagraficaExecuted)

public void OnAddEnagraficaExecuted(AnagraficaEntity parameter)

When I show the View I get this error "Unable to cast object of type 'System.String' to type 'EdilManager.Database.Entities.AnagraficaEntity'."




object parameter)



in Composite.Presentation.Commands.DelegateCommand class, the parameter is a string "001", before DelegateCommand got a string as parameter.

Composite ver. 2.0

Thanks to everyone


Apr 14, 2009 at 9:03 PM

Hi Armando,


I was able to reproduce the error you mention. I don't know your scenario exactly (where are you setting the command parameter?) but I guess the problem is the way you instantiate the DelegateCommand combined with the command parameter you use.


DelegateCommand is a generic class used to delegate execution to two methods (the executeMethod and the canExecuteMethod). The type of the parameters for these two method is defined by the generic type of the DelegateCommand class.


So when the you try to check if the command can execute the ICommand.CanExecute method is called. In the case of DelegateCommand class the CanExecute method is implemented in the following way:

        bool ICommand.CanExecute(object parameter)


            return CanExecute((T)parameter);



In your case the T type is AnagraficaEntity (as you define in it in the DelegateCommand  instantiation), so if parameter is of type String the error you mention will occur (.NET is unable to cast String into AnagraficaEntity).


Possible solutions:

·         Use an instance of AnagraficaEntity as the CommandParameter instead of a String.

o   Make sure the View is passing a value that is of this class instead of “001” which is a string. You may use a binding Converter to turn a string into a AnagraficaEntity if there is a way to convert to it from “001”.

·         Create the DelegateCommand using an object as parameter, and make the conversion to AnagraficaEntity inside the OnAddEnagraficaExecuted method:

                                new DelegateCommand <object>(OnAddEnagraficaExecuted)



Hope it helps!


Matias Bonaventura