Search code examples
mvvmprismdelegatecommandcanexecute

Making Command 1-time-executable


what is best practice to make a DelegateCommand from Prism framework in MVVM only one time executable in order to prevent click-spamming the button which may result in application crashes. many thanks!


Solution

  • Here is what I normally do:

    • You should have a property for what you are deleting. Use CanExecute
    • in your delegate command, watch the property if it is null? Use
    • ObserveProperty in your DelegateCommand and set it to What you are
    • deleting. In your DeleteCommandExecute set the property to null after deleting.

    here is an example

        private Class object;
        public Class Object
        {
            get { return object; }
            set { SetProperty(ref object, value); }
        }
        private DelegateCommand _delete;
        public DelegateCommand Delete =>
            _delete ?? (_delete = new DelegateCommand(ExecuteDelete, CanExecuteDelete)).ObservesProperty(()=> Object);
    
        void ExecuteDelete()
        {
            MyServices.Delete(Object);
            Object = null;
        }
    
        bool CanExecuteDelete()
        {
            return Object != null;
        }