Phil
Phil

Reputation: 532

MVVM Community Toolkit - Trigger "AlsoNotifyChangeFor"

In my sample Project I've got a model. The model looks like this:

public partial class BaseModel : ObservableObject, IBaseModel
{
    [ObservableProperty]
    private string id;

    [ObservableProperty]
    private string name;

    [ObservableProperty]
    private bool isActive;

    [ObservableProperty]
    private bool isNew;

    public BaseModel(bool isNew)
    {
        IsNew = isNew;
        IsActive = true;
    }
}

In my ViewModel I'm using this model like this:

    [AlsoNotifyChangeFor(nameof(CanDeleteSample))]
    [AlsoNotifyChangeFor(nameof(CanSaveSample))]
    [AlsoNotifyCanExecuteFor(nameof(SaveSampleCommand))]
    [AlsoNotifyCanExecuteFor(nameof(DeleteSampleCommand))]
    [ObservableProperty]
    private BaseModel sample = new();

If I first set "sample" with this "new()" initialization CanDeleteSample, CanSaveSample,... are notified and everything works fine. But if I change the value of, for example, "Name" no notification is done.

Is there a way to handle the notification if a property of "sample" has been changed? Further is there also a way to execute the notifications if I use a wrapped object withing the BaseModel class?

Thx

Upvotes: 0

Views: 3891

Answers (2)

Roberto Dalmonte
Roberto Dalmonte

Reputation: 31

I guess you should use this syntax:

[ICommand(CanExecute = nameof(CanShow))]
It will take care to match your command with the CanExecute.
You should reference the latest package:
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.0.0-build.94" />


[INotifyPropertyChanged]
public partial class MainWindowViewModel
{
    [ObservableProperty]
    [AlsoNotifyChangeFor(nameof(FullName))]
    [AlsoNotifyCanExecuteFor(nameof(ShowCommand))]
    private string firstName = string.Empty;

    [ObservableProperty]
    [AlsoNotifyChangeFor(nameof(FullName))]
    [AlsoNotifyCanExecuteFor(nameof(ShowCommand))]
    private string lastName = string.Empty;

    public string FullName => $"{LastName} {FirstName}";
    public bool CanShow { get => firstName.Length > 2 && lastName.Length > 2; }

    [ICommand(CanExecute = nameof(CanShow))]
    private void Show()
    {
        MessageBox.Show(FullName);
    }

    partial void OnFirstNameChanged(string value)
    {
        if (CanShow)
        {
            MessageBox.Show($"Execute Custom code on {value}");
        }
    }
}
enter code here

Upvotes: 2

Echo Lumaque
Echo Lumaque

Reputation: 51

Have you tried PropertyChanged.Fody? I believe it can do your requirements. Check below:

https://github.com/Fody/PropertyChanged#:~:text=Dependent%20properties%20%E2%80%94%20In,the%20target%20property).

Upvotes: 0

Related Questions