[WPF] 在ViewModel 中實現Command Binding

之前提及到在WPF 中利用Mode-View-ViewModel (MVVM) 中作EventHandling, 而一般的command binding 則須要自建class 去處理.DelegateCommand.cs

public class DelegateCommand : ICommand
    {
        private readonly Predicate<object> _canExecute;
        private readonly Action<object> _execute;

        public event EventHandler CanExecuteChanged;

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

        public DelegateCommand(Action<object> execute,
                       Predicate<object> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            return _canExecute(parameter);
        }

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

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }

利用 DelegateCommand Implement ICommand, 並於constructor 中加入Execute() 及CanExecute().

而叫用時, 在ViewModel 中則使用方法如下: 

public DelegateCommand SaveCommand;
        protected void SaveCommandExecute(object parameter)
        {
            // Command action.
        }
        protected bool SaveCommandCanExecute(object parameter)
        {
            // Command can execute or not.
            return true;
        }
        

        public MainWindowViewModel() : base()
        {
            // Define command and set property change handling.
            SaveCommand = new DelegateCommand(SaveCommandExecute, SaveCommandCanExecute);
            this.PropertyChanged += MainWindowViewModel_PropertyChanged;
        }

        private void MainWindowViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            // Fire event to execute CanExecute().
            SaveCommand.RaiseCanExecuteChanged();
        }

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.