单个绑定的多个验证规则

时间:2017-08-23 09:30:12

标签: c# wpf validation

单个绑定可以使用多个验证规则吗? 我尝试仅使用XAML验证TextBoxBindingGroup似乎无法正常工作。

这是我的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) {
        [...]
    }
}

1 个答案:

答案 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>