2011-06-15 41 views

回答

0

您可以在绑定上添加ValidationRule。如果验证失败,默认ErrorTemplate将用于文本框,否则你也可以自定义...的ValidatonRule的

例如:

class MaxLengthValidator : ValidationRule 
{ 
    public MaxLengthValidator() 
    { 

    } 

    public int MaxLength 
    { 
     get; 
     set; 
    } 


    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
    { 
     if (value.ToString().Length <= MaxLength) 
     { 
      return new ValidationResult(true, null); 
     } 
     else 
     { 
      //Here you can also play the sound... 
      return new ValidationResult(false, "too long"); 
     } 

    } 
} 

以及如何将其添加到绑定:

<TextBlock x:Name="target" /> 
<TextBox Height="23" Name="textBox1" Width="120"> 
    <TextBox.Text> 
     <Binding Mode="OneWayToSource" ElementName="target" Path="Text" UpdateSourceTrigger="PropertyChanged"> 
      <Binding.ValidationRules> 
       <local:MaxLengthValidator MaxLength="10" /> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 
+0

而这种解决方案实际上并不看TextBox.MaxLength财产(我们使用,在运行时动态生成)它提示的问题,请问有效性规则失败触发声音反馈? – 2011-06-15 07:28:46

+0

有没有办法与文本框的MaxLength属性一起使用? – 2011-06-15 07:29:45

+0

通常不会触发声音,但您可以在代码中看到lilne“//您也可以在此播放声音...”。在那里你可以播放你想要的任何声音。 – fixagon 2011-06-15 07:32:38