C
C#5mo ago
Elio

✅ RelayCommand CanExecute MVVM

Hi, I'm using this nuget CommunityToolkit.Mvvm.Input to add my relaycommand. i've set CanExecute this way => AddThickCommand = new RelayCommand(AddThickCommand_Execute, () => CanAddThickness); My problem there is that canexecute is trigger only when i declare AddThickCommand and canexecute is never raised again even if the boolean CanAddThickness change. I'd like to update canexecute each time CanAddThickness change to enable or not the button. Any idea why this don't work with this package ?
4 Replies
Pobiega
Pobiega5mo ago
You need to notify the command that the bool has changed IRelayCommand.NotifyCanExecuteChanged Since you are already using CommunityToolkit.Mvvm, you could use the source generated version of this to get all this "for free"
internal partial class TestViewModel : ObservableObject
{
[RelayCommand(CanExecute = nameof(CanAddThickness))]
private void AddThickness()
{
}

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(AddThicknessCommand))]
private bool canAddThickness;
}
internal partial class TestViewModel : ObservableObject
{
[RelayCommand(CanExecute = nameof(CanAddThickness))]
private void AddThickness()
{
}

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(AddThicknessCommand))]
private bool canAddThickness;
}
this would add a AddThicknessCommand public property that has a CanExecute that depends on the CanAddThickness observable property. When that property changes, the command will re-evaluate if it can execute or not.
Elio
Elio5mo ago
oh didn't know we could add anotations with this nuget i'll take a look thanks !!
Pobiega
Pobiega5mo ago
yea the source generator for it is... amazing it writes all the boilerplate code for you
Elio
Elio5mo ago
that is a bit tricky cause some code aren't wrote and you need to know that the properties is automatically generated, it will be perfect after sometime using it. Thanks !