2013-01-23 17 views
5

Jestem newbie do WPF.In mojego UserControl, mam 8 etykiet i jego odpowiednich 8 otaczaniem następująco:ValidationRule dla WPF pole tekstowe

1.Label : abc 2.Label : def 
    TextBox1 :  TextBox2 : 

3.Label :xyz 4. Label : ghi 
    Textbox3 :  TextBox4 : 

Każda z tych właściwości text tekstowe powinny zawierać tekst kończąc odpowiedniej etykiety nazwa dla TextBox1.text powinna być xxxx.abc, TextBox2.text powinna być xxxx.def i tak dalej.if nie pole tekstowe powinno mieć czerwoną obwódkę.

Mam nadzieję, że jestem jasny ze szczegółami.Tak Czy muszę napisać inny ValidationRule dla każdego pola tekstowego ??

Dowolne dane wejściowe?

Odpowiedz

21

Dlaczego nie mają jedną ValidationRule wdrożenia, z właściwością odsłaniając co pole powinno kończyć, np:

public class EndsWithValidationRule : ValidationRule 
{ 
    public string MustEndWith { get; set; } 

    public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
    { 
     var str = value as string; 
     if(str == null) 
     { 
      return new ValidationResult(false, "Please enter some text"); 
     } 
     if(!str.EndsWith(MustEndWith)) 
     { 
      return new ValidationResult(false, String.Format("Text must end with '{0}'", MustEndWith)); 
     } 
     return new ValidationResult(true, null); 

    } 
} 

Następnie można użyć tego tak:

<TextBox x:Name="TextBox1"> 
    <TextBox.Text> 
     <Binding Path="BoundProperty1" UpdateSourceTrigger="PropertyChanged"> 
      <Binding.ValidationRules> 
       <local:EndsWithValidationRule MustEndWith=".def" /> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 

<TextBox x:Name="TextBox2"> 
    <TextBox.Text> 
     <Binding Path="BoundProperty2" UpdateSourceTrigger="PropertyChanged"> 
      <Binding.ValidationRules> 
       <local:EndsWithValidationRule MustEndWith=".abc" /> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 
Powiązane problemy