3

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?

GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103

3 Answers3

3

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.

RQDQ
  • 15,461
  • 2
  • 32
  • 59
1

One option is to abandon commanding which has it's limitations, and use another mechanism such as Actions provided by Caliburn.Micro. Then, you just need your view model verb:

public void Save()
{
}

<Button x:Name="Save">Save</Button>
devdigital
  • 34,151
  • 9
  • 98
  • 120
0

I was using something like:

 public ICommand StopCommand 
 { 
     get{return new RelayCommand(OnStop);}
 }
Bolu
  • 8,696
  • 4
  • 38
  • 70