What I want to do is fairly simple however I have not seen examples online with respect on how to do it. I want an 'Update' button to become enabled if a field has been changed.
Context: I have a WPF form which updates a row in a database. I do not want the user to be able to click the 'Update' button unless he/she has modified some form value. I am using the MVVM pattern and have 4 properties which can be updated (Name, Address, Telephone and Email). Unless the user changes one of these properties, I do not want the Update button enabled.
Thanks!
Command code (I am unsure as to what kind of validation to put in the CanExecute)
public ICommand UpdateCommand
{
get;
internal set;
}
private void CreateUpdateCommand()
{
UpdateCommand = new RelayCommand(UpdateExecute, CanExecuteUpdateCommand);
}
private void UpdateExecute(object obj)
{
ClientModel.UpdateClient(_selectedClient);
}
private bool CanExecuteUpdateCommand(object obj)
{
return true;
}
Hi you can have a bool flag like hasChanges which is false initially.and in the setter of your modifiable properties you set it true and after updating set it false again.and in CanExecute return this hasChanges instead of true. Suppose you have property Name
private bool hasChanges=false;
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
hasChanges = true;
Notify("Name");
}
}
private bool CanExecuteUpdateCommand(object obj)
{
return hasChanges;
}
private void UpdateExecute(object obj)
{
ClientModel.UpdateClient(_selectedClient);
hasChanges=false;
}
I hope you got an idea.