CommunityToolkit / MVVM-Samples

Sample repo for MVVM package
Other
1.11k stars 222 forks source link

Feature Request: Provide us with CanExecuteDependsOn(nameof(AnObservableProperty)) attribute #136

Closed suugbut closed 3 months ago

suugbut commented 3 months ago

In my opinion ObservableProperty (as a publisher) should not know anything about ICommand (as a subscriber). So the following

public partial class PersonViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(SaveCommand))]
    private string name;

    [RelayCommand(CanExecute = nameof(CanSave))]
    private void Save() { }
    private bool CanSave() => !string.IsNullOrWhiteSpace(Name);
}

is more elegant if it can be written as follows.

public partial class PersonVM : ObservableObject
{
    [ObservableProperty]
    private string name;

    [RelayCommand(CanExecute = nameof(CanSave))]
    private void Save() { }

    [CanExecuteDependsOn(nameof(Name))] // <======= the requested attribute.
    private bool CanSave() => !string.IsNullOrWhiteSpace(Name);
}

With CanExecuteDependsOnAttribute we don't need to locate and decorate ObservableProperty whenever commands depend on it. It is more convenient if we place all setup related to a command in one place rather than two places spanned across multiple lines.

Any comments are welcome.