CommunityToolkit / CommunityToolkit/dotnet

Allow ability to raise CanExecuteChanged event of all commands for any property change

Open
#1,041 0 comments 0 reactions 0 assignees View on GitHub
feature request :mailbox_with_mail:
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

### Overview

I've found that I frequently have long lists of commands to update when properties change. It might be nice to be able to flag a class to raise CanExecuteChanged events for all commands whenever any property changes, then you wouldn't have to worry about remembering each command for each dependent property.

I think it would cut down on a decent amount of boilerplate with a fairly minor performance hit from unnecessarily calling CanExecute.

### API breakdown

I think the API would just be an attribute you can add to an ObservableObject like this:
```csharp
[AlwaysNotifyCanExecute]
public partial class ViewModel : ObservableObject
{
...
}
```

### Usage example

```csharp
[AlwaysNotifyCanExecute]
public partial class ViewModel : ObservableObject
{
public IRelayCommand DoThing1Command { get; }

[RelayCommand]
public void DoThing2() { }
}
```

would generate the following code:

```csharp
partial class ViewModel
{
protected overrides void OnPropertyChanged(PropertyChangedEventArgs args)
{
base.OnPropertyChanged(args);
DoThing1Command.NotifyCanExecuteChanged();
DoThing2Command.NotifyCanExecuteChanged();
}
}
```

### Breaking change?

No

### Alternatives

Edit:

You could also require/allow the attribute to take in the command names that you want to always update, ie:

```csharp
[AlwaysNotifyCanExecuteChanged(nameOf(DoThing1Command))]
public partial class ViewModel : ObservableObject
```

or maybe place the attribute on each command or tie it in to the `RelayCommandAttribute`:

```csharp
public partial class ViewModel : ObservableObject
{
[AlwaysNotifyCanExecute]
public IRelayCommand DoThing1Command { get; }

[RelayCommand(AlwaysNotifyCanExecute = true)]
public void DoThing2() { }
}
```

### Additional context

Since this is an opt-in feature, there shouldn't be breaking changes and it makes it clear at the top of the class what is happening behind the scenes.

### Help us help you

No, just wanted to propose this

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.