bossman1111 bossman1111 - 3 months ago 32
C# Question

delegate command with function with parameter

ModelRequestCommand = new DelegateCommand(PopulateModelRequest);


has no error and is fine, but I want to pass a parameter (int ProgramID) into populate model request. ProgramID is define by

this.ProgramId = ProgramID;


It gives an error when I try

ModelRequestCommand = new DelegateCommand(PopulateModelRequest(int ProgramID);


how do i go about this?

a button is binding to ModelRequestCommand in WPF

Answer

First, the code you wrote was nonsense, you tried to declare a parameter during a function invocation. You then tried to pass the result of that invocation (which should have been void) to a constructor expecting an Action<object> or possibly an Action delegate. You just can't do that.

Second, The ICommand interfaces Execute method (which is really what you are implementing) looks like this:

void Execute(object parameter)

Where parameter is passed via the CommandParameter property on the calling object (ie, a Button). The DelegateCommand object implements this and calls the delegate passed on the constructor with the same arguments (some versions of that class will allow you to pass a simple Action and DelegateCommand ignores parameter for you).

To fix it, either pass ProgramID on CommandParameter and do this:

private void PopulateModelRequest(object parameter)
{
   int programId = (int)parameter;
}

or something like

new DelegateCommand(() => PopulateModelRequest(ProgramId));

private void PopulateModelRequest(int programId)
{
}

The second is creating a closure over ProgramId, so if you would have access to that field anyways in your method, just use it instead of passing it in.

Comments