1
我有一個簡單的WPF應用程序,如果窗體有錯誤,我試圖關閉保存按鈕。wpf mvvm錯誤驗證
問題是,雖然它的驗證看起來很完美,但我不知道爲什麼,但我總是從負責檢查錯誤的方法中得到錯誤。
讓我通過提供代碼更清楚。
這是從MainWindow.Xaml.cs
private readonly HashSet<ValidationError> errors = new HashSet<ValidationError>();
private Lazy<MainWindowViewModel> viewModel;
public MainWindow() {
InitializeComponent();
InitializeValidaton();
}
void InitializeValidaton() {
viewModel = new Lazy<MainWindowViewModel>();
Validation.AddErrorHandler(this, ErrorChangedHandler);
}
private void ErrorChangedHandler(object sender, ValidationErrorEventArgs e) {
if (e.Action == ValidationErrorEventAction.Added) {
errors.Add(e.Error);
} else {
errors.Remove(e.Error);
}
//I set a breakpoint here and it returns the correct value. False if it has errors and True if not
viewModel.Value.IsValid = !errors.Any();
}
代碼這是爲按鈕
public ICommand SaveItem {
get { return new RelayCommand(SaveItemExecute,CanSaveItem); }
}
private bool CanSaveItem() {
return IsValid;
}
//I set up here a breakpoint and it returns the correct value just once.
//The application looked up on CanSaveItem all the time and except the first time, it returns wrong value
private bool _isValid;
public bool IsValid {
get { return _isValid; }
set {
_isValid = value;
RaisePropertyChanged("IsValid");
}
}
驗證規則
[Required(ErrorMessage = "Please enter Title")]
[StringLength(100, ErrorMessage = "The maximum length is 100")]
string Name { get; set; }
我不命令不知道它是否可以kes任何意義,但我想停用的按鈕在UserControl中。
我不明白爲什麼canExecute方法在userControl中觸發多次。如果我使用了什麼方法,它有相同的反應。我提到了userControl,因爲如果我在mainWindow中使用相同的方法(在ICommand中),它只觸發一次
如果有人能幫助我,我將不勝感激。
謝謝
也許它不會因爲2級參考Value.IsValid工作。嘗試手動更新命令,類似於「RaisePropertyChanged(」SaveItem「)」。 – vorrtex 2011-02-03 15:02:16
@vorrtex你能提出什麼建議嗎? – StrouMfios 2011-02-03 16:58:46