Got this to work with help from this post. I also added a HasValidData
property to ProjectUI
as it should self-validate itself. Posting full code that works.
ProjectUI:
public partial class ProjectUI: ObservableObject
public int Id { get; set; }
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasValidData))]
private ClientModel _client;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasValidData))]
private string _name;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasValidData))]
private DateTime? _startDate;
public bool HasValidData => Client != null &&
!string.IsNullOrEmpty(Name) &&
StartDate != null;
For the ViewModel, CanExectue
needs to be an ObservableProperty
that gets set via the ProperyChanged
Event. Add an Event Handler to the constructor or an OnLoaded
method. Make sure that Project object is initialized else you will get an exception
public partial class ViewModel
[ObservableProperty]
private ProjectUI _project;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ExecuteCommand))]
private _canExecute;
' It would be better if this was behind a RelayCommand bound to the Views Loaded Event.
But this is the easiest way to demonstrate how to solve the problem I am facing.'
public ViewModel()
{
Project = new ProjectUI();
Project.PropertyChanged += (s, e) =>
{
CanExecute = Project.HasValidData;
};
}
[RelayCommand(CanExecute = nameof(CanExecute))]
private async void Execute()
'...Code that does stuff [not important]