Home > front end >  C# WPF Declare an ICommand in a single line
C# WPF Declare an ICommand in a single line

Time:11-11

I'm in the process of learning WPF and the MVVM design pattern. Currently the code in my ViewModel for a delete customer command looks like this:

    public class vmCustomers : INotifyPropertyChanged
    {
...
        private ICommand _commandDeleteCustomer = null;
...
        public ICommand CommandDeleteCustomer
        {
            get
            {
                if (_commandDeleteCustomer == null)
                    _commandDeleteCustomer = new RelayCommand<object>(DeleteCustomerAction, DeleteCustomerPredicate);
                return _commandDeleteCustomer;
            }
        }

        private void DeleteCustomerAction(object o)
        {
            ...stuff...
        }

        private bool DeleteCustomerPredicate(object o)
        {
            ...stuff...
            return true;
        }
    }

I'd like to slim down the declaration of the ICommand to something like this so that I can reduce the coding overhead for each command:

public readonly ICommand CommandDeleteCustomer = new RelayCommand((obj) => DeleteCustomerAction(obj), (obj) => DeleteCustomerPredicate(obj));

But I get this error:

A field initializer cannot reference the non-static field, method, or property vmCustomers.DeleteCustomerAction(object)

Is there a way I can declare the ICommand in a single line of code so that I can simply focus on business-related code rather than repeated infrastructure code.

CodePudding user response:

Declare a readonly auto-implemented property

public ICommand CommandDeleteCustomer { get; }

and move the initialization statement to the view model constructor

public VmCustomers()
{
    CommandDeleteCustomer = new RelayCommand(...);
}
  • Related