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?

有帮助吗?

解决方案

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.

其他提示

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>

I was using something like:

 public ICommand StopCommand 
 { 
     get{return new RelayCommand(OnStop);}
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top