0

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.

Ievgen Martynov
  • 7,870
  • 8
  • 36
  • 52

2 Answers2

1

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).

Ievgen Martynov
  • 7,870
  • 8
  • 36
  • 52
0

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.

Joel Lucsy
  • 8,520
  • 1
  • 29
  • 35
  • Joel, can you tell more about this? If I use separate thread for DoSearch() and include _isSearchInProgres inside method, It works good, but only first time. Later I should click on UI to update it. – Ievgen Martynov Feb 01 '12 at 14:44
  • Are you using INotifyPropertyChanged for the class that contains _isSearchInProgress, and consequently, is _isSearchInProgress a public property and are you firing PropertyChanged when it changes? – Joel Lucsy Feb 01 '12 at 16:47
  • _isSearchInProgress is a private field and it is not bound to UI, that's why INotifyPropertyChanged would not help me. This is big puzzle why it doesn't work in main thread at all and works partially in separate one. – Ievgen Martynov Feb 02 '12 at 09:09