Click here to Skip to main content
15,899,025 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Would just like to know if the below is a Valid way to assign a method to an ICommand.

public RelayCommand<object> CommandName
{
    get 
    {
       return new RelayCommand<object>(methodname);
    }
}

// or anonymously
public RelayCommand<object> CommandName
{
    get 
    {
       return new RelayCommand<object>(o =>
       {

       });
    }
}


What I have tried:

I'm currently doing this
public RelayCommand CommandName { get; private set; }

// Called from Constructor
private void SetupCommands()
{
    CommandName = new RelayCommand<object>(methodname);
    
    // or anonymously
    CommandName = new RelayCommand(o =>
    {

    });
}
Posted
Updated 16-Mar-20 6:54am
Comments
[no name] 16-Mar-20 10:55am    
If it "works", it's valid.

1 solution

My preference is to use the ICommand interface where possible rather than a class that implements the interface. The technique results in more loosely coupled code. Something like this.

C#
private ICommand cancelCommand;
public ICommand CancelCommand
 {
  get
   {
    return cancelCommand ?? (cancelCommand = new RelayCommand(MyCancelMethod));
   }
 }

By using the null-coalescing operator there is no need for a 'setter' and the RelayCommand is instantiated where it is used rather than in a constructor.

 
Share this answer
 

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