Ievgen
Ievgen

Reputation: 8086

WPF. RelayCommand - CanExecute false, while Execute is processing

I want to disable a button, while its command is processing.

    public ICommand Search { get; set; }

    private void InitilizeSearchCommand()
    {
        Search = new RelayCommand<string>(
            param => DoSearch(param), 
            param => !_isSearchInProgress);
    }

How can I modify _isSearchInProgress? I could not do it inside "Execute" delegate because it executes from place (RelayCommand object) where the field is not accessible (if my understanding is true):

Search = new RelayCommand<string>(
            param =>
                {
                    _isSearchInProgress = true;
                    DoSearch(param);
                    _isSearchInProgress = false;
                },
            param => !_isSearchInProgress);

Thanks in advance for any help.

Upvotes: 0

Views: 1433

Answers (2)

Ievgen
Ievgen

Reputation: 8086

The solution to solve the problem:

Search = new RelayCommand<string>(
            backgroundWorker.RunWorkerAsync,
            param =>
                {
                    CommandManager.InvalidateRequerySuggested();
                    return !_isSearchInProgress;
                });

The

CommandManager.InvalidateRequerySuggested();

should be added to CanExecute method, not in Execute. _isSearchInProgress is updated inside DoSearch() that is run in separate thread (backgroundWorker.RunWorkerAsync in my case).

Upvotes: 1

Joel Lucsy
Joel Lucsy

Reputation: 8706

Unless you are running in a background thread or Task, the GUI won't be asking for updates from the CanExecute part. If you are doing stuff in the background, just make sure _isSearchInProgress is not created inside the any function, but part of the class.

Upvotes: 0

Related Questions