C#: Disable button during search/calculation

前端 未结 4 1065
梦如初夏
梦如初夏 2021-01-16 12:58

I have a search dialog where I want to disable the search button during the search. This is the current code but the button does not get deactivated

View:

         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 13:42

    I've made an AsyncDelegateCommand for that reason (based on famous DelegateCommand), it internally disable command (in UI) during executing command action:

    public class AsyncDelegateCommand : ICommand
    {
        readonly Action _execute;
        readonly Predicate _canExecute;
        bool _running;
    
        public event EventHandler CanExecuteChanged;
    
        public AsyncDelegateCommand(Action execute, Predicate canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }
    
        public bool CanExecute(object parameter)
        {
            return (_canExecute == null ? true : _canExecute(parameter)) && !_running;
        }
    
        public async void Execute(object parameter)
        {
            _running = true;
            Update();
            await Task.Run(() => _execute(parameter));
            _running = false;
            Update();
        }
    
        public void Update()
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged(this, EventArgs.Empty);
        }
    }
    
    
    

    xaml:

    ViewModel:

    AsyncDelegateCommand SomeCommand { get; }
    
        // in constructor
        SomeCommand = new AsyncDelegateCommand(o =>  { Thread.Sleep(5000); }); // code to run
    

    提交回复
    热议问题