xyann00
xyann00

Reputation: 25

Simple way to create a command

I am new to C# and I need to create simple binding command for one button. I have been reading a lot of articles for last hours but it simply got me more confused.

I have an WPF window (let's say Window1) where I have button "AddCustomer". What is the simplest way to create command for it? (By simplest I mean easy to understand)

In every article they were doing it differently. I need you to show me also how to bind it in xaml, more detailed the better... like I said, I am new.

Thank you for your help.

Upvotes: 0

Views: 121

Answers (2)

Mashton
Mashton

Reputation: 6415

Here's my take on it, the following is 'simplest' because you are leveraging the Prism library and so the amount of code you write is small. Use the nuget manager to add Prism to your project if you're not already using it ...

The xaml:

<Button Command="{Binding AddCustomerCommand}" Content="Add Customer"/>

In your viewmodel: (1) Declare your command:

public ICommand AddCustomerCommand{ get; private set; }

(2) Define your command:

AddCustomerCommand= new DelegateCommand(AddCustomer);

(3) And create the method:

private void AddCustomer()
{
    //do your logic here
}

Extended version: You can pass a parameter from the xaml:

<Button Command="{Binding AddCustomerCommand}" CommandParameter={Binding SelectedItem, ElementName=MySelectorThingy} Content="Add Customer"/>

Remember to change the signature of your delegate and method:

AddCustomerCommand= new DelegateCommand<WhateverMyTypeIs>(AddCustomer);

private void AddCustomer(WhateverMyTypeIs selectedThing)
{
    //do your logic here
}

You can also define in the DelegateCommand when the button should be available (CanExecute), like the following:

public DelegateCommand AddCustomerCommand{ get; private set; }

AddCustomerCommand = new DelegateCommand(AddCustomer, AddCustomer_CanExecute);

And then define the method for deciding whether you can execute or not:

private bool AddCustomer_CanExecute()
{
    if (DateTime.Now.DayOfWeek.Equals(DayOfWeek.Monday))
      return true;
    else
      return false;
}

Upvotes: 1

J R B
J R B

Reputation: 2136

below is the complete solution for commands in WPF.

first create a class for execute the command.

 public class RelayCommand : ICommand
  {

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;
    private Action<object> _action;
    private bool _canSave;


    public RelayCommand(Action<object> execute) : this(execute, null) { }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null) throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }

    public RelayCommand(Action<object> action, bool CanSave)
    {

        this._action = action;
        this._canSave = CanSave;
    }


    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute(parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        add
        {
            CommandManager.RequerySuggested += value;
        }
        remove
        {
            CommandManager.RequerySuggested -= value;
        }
    }
    public void Execute(object parameter)
    {
        _execute(parameter);
    }

}

below is the ViewModel

 public FilterViewModel()
    {
     private RelayCommand _commandSave;
     public ICommand Save
      {
        get { 
           return _commandSave ?? (_commandSave = 
           new RelayCommand(param => SaveMethod(param), CanSave)); 
           }
       }

  private void SaveMethod 
    {
     //code for save
    }

   private Predicate<object> CanSave
    {
        get { return o => true; }
    }

  }

and finally using the command in XAML.

 <Button x:Name="btnSave" Content="Save" Command="{Binding Save}"  CommandParameter="PASS-PARAMETER-HERE" ></Button>

Upvotes: 2

Related Questions