'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
Solution 1:[1]
Have you tried PropertyChanged.Fody? I believe it can do your requirements. Check below:
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Echo Lumaque |
| Solution 2 | Roberto Dalmonte |
