Search code examples
c#mvvmreadabilityrelaycommand

Best / neatest way to declare RelayCommands


I've been trying to find a nice neat and succinct way to declare RelayCommands in my ViewModels.

The best I can come up with is:

public class MyViewModel
{
    public ICommand StopCommand { get; private set; }

    public MyViewModel()
    {
        StopCommand = new RelayCommand(OnStop);
    }

    private OnStop(object sender)
    {
         //hammertime
    }

}

What I'd really like to do it remove the two stage declaration/construction, something like:

public class MyViewModel
{
    public readonly ICommand StopCommand = new RelayCommand(OnStop);

    private OnStop(object sender)
    {
         //hammertime
    }
}

However, this fails to compile with

error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyViewModel.OnStop(object)'

It there a neater / "standard" way that people use?


Solution

  • I've used the first format you specified quite a bit and it works fine for me.

    Also - if you're using WPF, binding doesn't work with fields anyway so even if you can get the second approach to compile, it won't hook up to your UI.