Hello,
Welcome to our Microsoft Q&A platform!
The return value of the canSetName Func
cannot by updated automatically. Try adding a bool property in the MainVM class to receive the result of !string.IsNullOrWhiteSpace(FirstName) && !string.IsNullOrWhiteSpace(LastName)
code. Detect the property changed event of the FirstName and LastName property to update the value of the bool property.
Check the code:
public class MainVM : INotifyPropertyChanged
{
public ObservableCollection<string> Names { get; set; }
public Command MyCommand { get; set; }
public MainVM()
{
MyCommand = new Command(setName, canSetName);
Names = new ObservableCollection<string>();
}
void setName()
{
Names.Add(FirstName + " " + LastName);
FirstName = string.Empty; LastName = null;
}
bool canSetName()
{
return Result;
}
public string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
if (firstName != value)
{
firstName = value;
Result = !string.IsNullOrWhiteSpace(value) && !string.IsNullOrWhiteSpace(LastName) ? true : false;
OnPropertyChanged(nameof(FirstName));
}
}
}
public string lastName;
public string LastName
{
get
{
return lastName;
}
set
{
if (lastName != value)
{
lastName = value;
Result = !string.IsNullOrWhiteSpace(value) && !string.IsNullOrWhiteSpace(FirstName) ? true : false;
OnPropertyChanged(nameof(LastName));
}
}
}
public bool result;
public bool Result
{
get
{
return result;
}
set
{
if (result != value)
{
result = value;
MyCommand?.ChangeCanExecute();
OnPropertyChanged(nameof(Result));
}
}
}
void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
public event PropertyChangedEventHandler PropertyChanged;
}
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.