2017-11-22 19 views
0

무엇인가 잘못되었을 때 텍스트 상자의 유효성을 검사하려고합니다. 그 아이디어는 다음 TextBox가 경고 이미지를 가져야하는 것보다 잘못되었을 때입니다.유효성 검사시 TextBox에 경고 아이콘 추가

<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"> 
    <Validation.ErrorTemplate> 
     <ControlTemplate> 
      <StackPanel> 
       <!-- Placeholder for the TextBox itself --> 
       <AdornedElementPlaceholder x:Name="textBox"/> 
       <image source="some-Image.png" width="20" Height="20" /> 
      </StackPanel> 
     </ControlTemplate> 
    </Validation.ErrorTemplate> 
</TextBox> 

하지만 이미지가 표시되지 않는 것은 아이콘 테두리 만 표시합니다. AdornedElementPlaceholder을 올바르게 사용하고 있습니까? 작동 오류가 발생할 때 이미지를 표시

+0

코드가 씬하지 않은 이유는 코드를 사용하면 매우 쉽습니다. – tpbafk

답변

0

테스트 솔루션 :

public class IntegerValidationRule : ValidationRule 
{ 
    private int _min = int.MinValue; 
    private int _max = int.MaxValue; 
    private string _fieldName = "Field"; 
    private string _customMessage = String.Empty; 

    public int Min 
    { 
     get { return _min; } 
     set { _min = value; } 
    } 

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

    public string FieldName 
    { 
     get { return _fieldName; } 
     set { _fieldName = value; } 
    } 

    public string CustomMessage 
    { 
     get { return _customMessage; } 
     set { _customMessage = value; } 
    } 


    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
    { 
     int num = 0; 

     var val = (value as BindingExpression).DataItem; 

     if (!int.TryParse(value.ToString(), out num)) 
      return new ValidationResult(false, $"{FieldName} must contain an integer value."); 

     if (num < Min || num > Max) 
     { 
      if (!String.IsNullOrEmpty(CustomMessage)) 
       return new ValidationResult(false, CustomMessage); 


      return new ValidationResult(false, $"{FieldName} must be between {Min} and {Max}."); 
     } 

     return new ValidationResult(true, null); 
    } 
} 

단지에서 예를 수정 : 여기

<TextBox BorderThickness="0.8"> 
    <Validation.ErrorTemplate> 
     <ControlTemplate> 
      <StackPanel> 
       <AdornedElementPlaceholder/> 
       <Image Source="Image.jpg" Width="20" Height="20"/> 
      </StackPanel> 
     </ControlTemplate> 
    </Validation.ErrorTemplate> 
    <TextBox.Text> 
     <Binding Path="ValidationTest" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" ValidatesOnDataErrors="True"> 
      <Binding.ValidationRules> 
       <validation:IntegerValidationRule ValidationStep="CommittedValue" Min="1" Max="99999999"/> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 

을 그리고 내가이, 예를 들면 사용한 유효성 검사 규칙입니다 MSDN Docs
일부 메모 :
내가 유효 할 수 있도록 유효성 검사 규칙을 제공하지 않았습니다. 그것은 예상대로 작동하고 유효한 검증 결과를 생성합니다.
TextBox.Text 속성의 바인딩에는 유효성 검사 규칙이 포함되어 있지 않습니다.