2011-01-14 32 views
6

Yangın için özel bir doğrulama kuralı almaya çalıştığım Silverlight 4 uygulamasında basit bir sınama sayfası var.CustomValidation özniteliği işe yaramıyor gibi görünüyor

Bir TextBox'um ve bir Düğmem var ve bir TextBlock'ta doğrulama sonuçlarını gösteriyorum. Görünüm modelim, TextBox'un Text özelliğine bağlı olan bir Name özelliğine sahiptir. Name özelliği, [Required] ve [CustomValidation] iki doğrulama öznitelikleri var.

Gönder düğmesine bastığımda, Gerekli doğrulayıcı doğru şekilde tetiklenir, ancak özel geçerlilik denetleyicinin doğrulama yöntemindeki kesme noktası hiçbir zaman vurulmaz. İşte

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx görünümü modeli için kodudur:

<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> 
: Burada

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"; 
      } 
     } 
    } 
} 

görünümüdür bu yüzden ben çok dikkatli MS'nin örneğini takip düşünmek gibi ben göremiyorum

+0

Gerçek soruya dikey olarak, ancak FWIW, Char.IsUpper statik yöntemiyle denetimi yapabilirsiniz: http://msdn.microsoft.com/en-us/library/system.char.isupper(v=VS.100) .aspx –

cevap

11

Validator.TryValidateObject (http://msdn.microsoft.com/en-us/library/dd411803(v=VS.95).aspx) aşırı yüklenme için MSDN sayfasında belirtildiği gibi, yalnızca nesne düzeyi doğrulamaları bu yöntemle ve RequiredAttribute özellikleriyle işaretlenir.

da bir bool alır aşırı kullanmak, mülk seviyesinde doğrulamaları kontrol etmek Yani (http://msdn.microsoft.com/en-us/library/dd411772(v=VS.95).aspx)

o TryValidateObject için fazladan bir parametre olarak "doğru" geçen hem basit olmalıdır

+0

Çalıştı! Teşekkürler. –

+0

Kodda tam olarak ne yazdınız, böylece sizin için çalıştı? –

+0

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx adresinden ne yapmalıyım? –

11

Neden don' .. böyle özelliğini kendi Doğrulama oluşturmak

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; 
     } 
} 

t sonra

// 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); } 
    } 
gibi kullanırız
+1

Bunu [CustomValidation] özelliğine tercih ediyorum. –

İlgili konular