2011-01-14 78 views
6

我在Silverlight 4中的應用程序有一個簡單的測試頁面中,我試圖讓一個自定義的驗證規則開火。CustomValidation屬性似乎不工作

我有一個文本框和按鈕,和我在展示一個TextBlock驗證結果。我的視圖模型具有Name屬性,該屬性綁定到TextBox的Text屬性。我在Name屬性上有兩個驗證屬性,[Required][CustomValidation]

當我點擊提交按鈕,所需的驗證火災正確的,但我的自定義驗證程序的驗證方法從來沒有被擊中裏面的斷點。我不明白這是爲什麼,因爲我覺得我已經很認真遵循MS的例子:http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx

下面是視圖模型代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using GalaSoft.MvvmLight.Command; 

namespace MyProject 
{ 
    // custom validation class 
    public class StartsCapitalValidator 
    { 
     public static ValidationResult IsValid(string value) 
     { 
      // this code never gets hit 
      if (value.Length > 0) 
      { 
       var valid = (value[0].ToString() == value[0].ToString().ToUpper()); 
       if (!valid) 
        return new ValidationResult("Name must start with capital letter"); 
      } 
      return ValidationResult.Success; 
     } 
    } 

    // my view model 
    public class ValidationTestViewModel : ViewModelBase 
    { 
     // the property to be validated 
     string _name; 
     [Required] 
     [CustomValidation(typeof(StartsCapitalValidator), "IsValid")] 
     public string Name 
     { 
      get { return _name; } 
      set { SetProperty(ref _name, value,() => Name); } 
     } 

     string _result; 
     public string Result 
     { 
      get { return _result; } 
      private set { SetProperty(ref _result, value,() => Result); } 
     } 

     public RelayCommand SubmitCommand { get; private set; } 

     public ValidationTestViewModel() 
     { 
      SubmitCommand = new RelayCommand(Submit); 
     } 

     void Submit() 
     { 
      // perform validation when the user clicks the Submit button 
      var errors = new List<ValidationResult>(); 
      if (!Validator.TryValidateObject(this, new ValidationContext(this, null, null), errors)) 
      { 
       // we only ever get here from the Required validation, never from the CustomValidator 
       Result = String.Format("{0} error(s):\n{1}", 
        errors.Count, 
        String.Join("\n", errors.Select(e => e.ErrorMessage))); 
      } 
      else 
      { 
       Result = "Valid"; 
      } 
     } 
    } 
} 

這裏是視圖:

<navigation:Page x:Class="Data.Byldr.Application.Views.ValidationTest" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"> 
    <Grid Width="400"> 
    <StackPanel> 
     <TextBox Text="{Binding Name, Mode=TwoWay}" /> 
     <Button Command="{Binding SubmitCommand}" Content="Submit" /> 
     <TextBlock Text="{Binding Result}" /> 
    </StackPanel> 
    </Grid> 
</navigation:Page> 
+0

正交的實際問題,但FWIW你可以做通過Char.IsUpper靜態方法檢查:http://msdn.microsoft.com/en-us/library/system.char.isupper(v=VS.100 ).aspx – 2011-03-27 21:07:43

回答

11

正如在過載Validator.TryValidateObjecthttp://msdn.microsoft.com/en-us/library/dd411803(v=VS.95).aspx)的MSDN頁面上所述,只有對象級別的驗證使用此方法進行檢查,而對屬性使用RequiredAttribute。

要檢查屬性級別的驗證,使用重載也需要一個布爾(http://msdn.microsoft.com/en-us/library/dd411772(v=VS.95).aspx

所以它應該是爲傳遞「真」作爲一個額外的參數TryValidateObject簡單

+0

它的工作!謝謝。 – 2011-01-19 01:03:41

+0

你究竟在代碼中寫了什麼,以便它對你有用? – 2013-02-05 11:42:28

11

爲什麼不T優創建自己的驗證屬性這樣的..

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 

public class StartsCapital : ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      var text = value as string; 

      if(text == null) 
       return ValidationResult.Success; 

      if (text.Length > 0) 
      { 
       var valid = (text[0].ToString() == text[0].ToString().ToUpper()); 
       if (!valid) 
        return new ValidationResult("Name must start with capital letter"); 
      } 
      return ValidationResult.Success; 
     } 
} 

,然後用它像

// my view model 
public class ValidationTestViewModel : ViewModelBase 
{ 
    // the property to be validated 
    string _name; 
    [Required] 
    [StartsCapital] 
    public string Name 
    { 
     get { return _name; } 
     set { SetProperty(ref _name, value,() => Name); } 
    }