2011-08-30 6 views
0

제 질문은 바인딩 검증을 위해 xaml을 어떻게 대체 할 수 있습니까? 예 XAMLXAML없이 바인딩 유효성 검사

<TextBox.Text> 
     <Binding Path="Age" UpdateSourceTrigger="PropertyChanged"> 
      <!--<Binding Path="Age" NotifyOnValidationError="True">--> 
      <Binding.ValidationRules> 
      <!--<ExceptionValidationRule />--> 
      **<local:NumberRangeRule Min="0" Max="128" />** 
      </Binding.ValidationRules> 
     </Binding> 
</TextBox.Text> 

경우 C# 코드

Binding bindtext = new Binding(); 
Person person = new Person("Tom",12); 

bindtext.Source = person; 
bindtext.Mode = BindingMode.TwoWay; 
bindtext.Path = new PropertyPath("Age"); 

bindtext.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 

bindtext.ValidatesOnExceptions = true; 

ageTextBox.SetBinding(TextBox.TextProperty, bindtext); 

에 ////////////////////////// //

사용자 검증 클래스를 정의

public class NumberRangeRule : ValidationRule { 
    int _min; 
    public int Min { 
     get { return _min; } 
     set { _min = value; } 
    } 

    int _max; 
    public int Max { 
     get { return _max; } 
     set { _max = value; } 
    } 

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { 
     int number; 
     if(!int.TryParse((string)value, out number)) { 
     return new ValidationResult(false, "Invalid number format"); 
     } 

     if(number < _min || number > _max) { 
     string s = string.Format("Number out of range ({0}-{1})", _min, _max); 
     return new ValidationResult(false, s); 
     } 

     //return new ValidationResult(true, null); 
     return ValidationResult.ValidResult; 
    } 
    } 

////////////////////////////////

하지만 텍스트 검증에 바인딩 유효성 검사를 사용하려면 어떻게해야합니까?

답변

2

그냥 새 규칙을 추가 하시겠습니까?

bindtext.ValidationRules.Add(new NumberRangeRule() { Min = 0, Max = 128 }); 
+0

감사합니다. 그것은 작동합니다. – flyKite

+0

@ user838053 : 기꺼이 도와 줬습니다. [수락] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) 내 대답은 왼쪽에있는 체크 표시 개요를 클릭하여 . –

관련 문제