我正在創建一個MVVM Silverlight應用程序,並試圖將驗證添加到我的模型中。自定義驗證僅運行一次
在這個特殊的情況下,我有多個電話號碼框,並要求至少輸入一個電話號碼。爲了方便我在裝有CustomValidation屬性的模型上使用我的屬性(HomePhone,WorkPhone,MobilePhone和OtherPhone)。
示例屬性:
private string _otherPhone;
[CustomValidation(typeof(MyModel), "ValidatePhoneNumbers")]
public string OtherPhone
{
get { return _otherPhone; }
set
{
if (_otherPhone == value) return;
_otherPhone = value;
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "OtherPhone" });
RaisePropertyChanged(() => HomePhone);
RaisePropertyChanged(() => WorkPhone);
RaisePropertyChanged(() => MobilePhone);
RaisePropertyChanged(() => OtherPhone);
}
}
隨着自定義的驗證本身:
public static ValidationResult ValidatePhoneNumbers(string number, ValidationContext validationContext)
{
MyModel myModel = (MyModel)validationContext.ObjectInstance;
return string.IsNullOrEmpty(myModel.HomePhone) && string.IsNullOrEmpty(myModel.WorkPhone) && string.IsNullOrEmpty(myModel.MobilePhone) && string.IsNullOrEmpty(myModel.OtherPhone)
? new ValidationResult("At least one phone number must be entered")
: ValidationResult.Success;
}
我已經確保了備份存儲在屬性setter設置運行驗證之前,要確保ValidatePhoneNumbers方法可以檢查最新的值。
當我嘗試保存我的模型時,我在View中的所有綁定上執行UpdateBindingExpression。現在這可以正常工作我試圖保存的第一個時間,並且所有四個字段都突出顯示爲有錯誤。
但是,如果我再次嘗試保存,所有字段都標記爲通過驗證,並且ValidatePhoneNumbers中的斷點永遠不會被命中。爲什麼是這樣?
感謝
翻轉你如果....如果(value.equals(_otherPhone){_otherPhone =值; //等}!,那之後做你想做的東西做是否值被設置爲已經是相同的或不是 – 2011-05-11 11:30:01
但是,這將實現什麼?如果確保PropertyChanged沒有被觸發,如果它沒有被改變 – 2011-05-11 14:01:17
如果你重讀它的評論*然後做如果你不想做RaisePropertyChanged項目,他們會進入if語句,而不是之後。基本上:'if(!value。 Equals(_otherPhone){//如果設置了值,就在這裏做東西} //在你想要做的事情之外做東西,不管它是什麼樣的。' – 2011-05-11 14:43:42