WPF – Command

The command pattern is a common software design pattern that allows you to easily encapsulate the logic.

The ICommand interface requires CanExecute and Execute methods, as well as a CanExecuteChanged event handler that signals when the can execute status has changed:

public interface ICommand
{
   bool CanExecute(object parameter);
   event EventHandler CanExecuteChanged;
   void Execute(object parameter)
}

Implementation of ICommand Interface:

using System;
using System.Windows.Input;

namespace CommandAndMessenger.Common
{
    internal class CustomCommand : ICommand
    {
        private Action<object> execute;
        private Predicate<object> can;

        public CustomCommand(Action<object> execute, Predicate<object> can)
        {
            this.execute = execute;
            this.can = can ?? ((x) => true);
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }

            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object parameter)
        {
            return can(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}

Example:

using CommandAndMessenger.Common;
using CommandAndMessenger.Model;
using System.Windows.Input;

namespace CommandAndMessenger.ViewModel
{
    internal class Main: SimpleItem
    {
        public Main():
            base("My Sample Application")
        {
            OpenFileCommand = new CustomCommand((x) => FileOpen(x), (x)=> true);
            CloseApplicationCommand = new CustomCommand((x) => CloseApplication(x), (x) => true);
        }

        public ICommand OpenFileCommand { get; set; }

        public ICommand CloseApplicationCommand { get; set; }

        private void FileOpen(object para)
        {
           // Code
        }

        private void CloseApplication(object para)
        {
           // Code            
        }
    }
}

XAML:

<button.contextmenu>
  <contextmenu>
     <menuitem header="Open File" command="{Binding OpenFileCommand}">
     <menuitem header="Close Application" command="{Binding CloseApplicationCommand}">
  </menuitem></menuitem></contextmenu>
</button.contextmenu>

Leave a Reply

Your e-mail address will not be published. Required fields are marked *