单个绑定可以使用多个验证规则吗?
我尝试仅使用XAML验证TextBox
,BindingGroup
似乎无法正常工作。
这是我的XAML:
<TextBox>
<TextBox.Text>
<Binding Path="Title" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
<TextBox.BindingGroup>
<BindingGroup NotifyOnValidationError="True">
<BindingGroup.ValidationRules>
<rule:CantBeEmpty ValidatesOnTargetUpdated="True" />
<rule:CantBeMoreThanXCharacters
CharacterLimit="30"
ValidatesOnTargetUpdated="True" />
<BindingGroup.ValidationRules/>
</BindingGroup>
</TextBox.BindingGroup>
</TextBox>
rule
命名空间引用xmlns:rule="clr-namespace:MyApp.Views.ValidationRules"
的位置
这些规则遵循标准语法:
public class CantBeEmpty : ValidationRule {
public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
[...]
}
}
答案 0 :(得分:5)
您是否尝试将验证规则添加到绑定中?:
<TextBox>
<TextBox.Text>
<Binding Path="Title" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<rule:CantBeEmpty ValidatesOnTargetUpdated="True" />
<rule:CantBeMoreThanXCharacters CharacterLimit="30" ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>