Igor Kondrasovas
Igor Kondrasovas

Reputation: 1671

Asynchronous UI Pattern on UWA

I am following this great article from Stephen about asynchronous UI, but unfortunately this does not apply to Universal Windows Apps, since CommandManager class is not available.

How can I workaround this limitation?

This is the base type for Async Commands:

public abstract class AsyncCommandBase : IAsyncCommand
{
  public abstract bool CanExecute(object parameter);
  public abstract Task ExecuteAsync(object parameter);
  public async void Execute(object parameter)
  {
    await ExecuteAsync(parameter);
  }
  public event EventHandler CanExecuteChanged
 {
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
 }
  protected void RaiseCanExecuteChanged()
 {
CommandManager.InvalidateRequerySuggested();
}
}

Upvotes: 0

Views: 94

Answers (1)

Tseng
Tseng

Reputation: 64150

As pointed in the comments, this "pattern" shouldn't be used because of it's impact on performance when you have many commands registered.

Any call to CommandManager.InvalidateRequerySuggested() will force WPF to validate every single registered command and it's CanExecute(...) methods.

Instead, just declare the event and only let WPF register to it

public abstract class AsyncCommandBase : IAsyncCommand
{
    ...
    public event EventHandler CanExecuteChanged;
    public void RaiseCanExecuteChanged()
    {
        // C# 6.0, otherwise assign the handler to variable and do null check
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
    ...
}

Whenever you want to invalidate the command you still just use command.RaiseCanExecuteChanged();. If you want to trigger revalidation of multiple commands, you need to manage it yourself (i.e. creating a CompoundCommand or something similar where you register your commands to groups).

Upvotes: 1

Related Questions