为什么不使用一个ValidationRule
实现,其属性公开字段应以什么结尾,例如:
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);
}
}
然后你可以像这样使用它:
<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>