Dans mon ViewModel, j'ai implémenté l'interface IDataErrorInfo (avec INotifyPropertyChanged). La validation d'entrée fonctionne comme prévu, je n'ai aucun problème là-bas.Liaison de commandes WPF avec validation d'entrée - comment activer le bouton "Enregistrer" uniquement si toutes les entrées sont valides
Je cette propriété dans le cadre de IDataErrorInfo public string Error { get { return this[null]; } }
À ma connaissance, Error
devrait être vide si toutes les entrées validées passent la validation, donc je passe ce que ma méthode de CanExecute
return !string.IsNullOrEmpty(Error);
Mais, mon bouton « Enregistrer » n'est jamais activé. Mon point de vue est que CanExecuteChanged
ne devient jamais truite. Si c'est vrai, où et comment devrais-je le déclencher?
Ceci est ma classe RelayCommand. J'ai essayé d'autres moyens de mise en œuvre, mais les résultats étaient les mêmes. Je pense que cela fonctionne, car le bouton "Enregistrer" est activé si je ne passe pas la méthode CanExecute au constructeur.
public class RelayCommand : ICommand
{
private readonly Action execute;
private readonly Func<bool> canExecute;
public RelayCommand(Action execute, Func<bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return canExecute == null || canExecute();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter) { execute(); }
}
Le bouton "Enregistrer":
<Button Content="Save" Command="{Binding InsertCommand}"/>
InsertCommand:
public RelayCommand InsertCommand { get; internal set; }
Dans le constructeur ViewModel:
InsertCommand = new RelayCommand(ExecuteInsert, CanExecuteInsert);
CanExecute:
bool CanExecuteInsert()
{
return !string.IsNullOrEmpty(Error);
}
Afficher InsertCommand comment il a été initialisé et son CanExecute –
@lll Ajouté à la fin. –