简体   繁体   English

我如何强制WPF ValidationRules绑定?

[英]How do i force wpf ValidationRules binding?

I have a textbox for example that is bound via the mvvm pattern like this: 我有一个文本框,例如通过mvvm模式绑定的文本框,如下所示:

<TextBox VerticalAlignment="Center" Grid.Column="2" Grid.Row="1" Validation.ErrorTemplate="{StaticResource ValidationErrorTemplate}">
            <TextBox.Text>
                <Binding Path="Entity.LastName" NotifyOnValidationError="True">
                    <Binding.ValidationRules>
                        <validations:MandatoryValidationRule/>

This specific rule checks if any value was entered to the textbox. 此特定规则检查是否在文本框中输入了任何值。 However, this rule is activated only when a user enters some text and then deletes it. 但是,仅当用户输入一些文本然后将其删除时,才会激活此规则。 Most times, when a user leaves out a blank field, its because he forgot to fill it. 大多数情况下,当用户留下空白字段时,这是因为他忘记填写该字段。

So, how can i, from the view model, force all validation rules to be checked before i allow the user to actually save the data? 那么,在允许用户实际保存数据之前,如何从视图模型强制检查所有验证规则?

It would be also nice if i could somehow do it to all the controls at once. 如果我能以某种方式一次对所有控件进行操作,那也很好。

Thank u. 感谢你。

You can force the rules to update automatically once the Window has bee loaded so that the blank fields will indicate an error: 您可以在加载“窗口”后强制规则自动更新,以便空白字段指示错误:

public void Window_Loaded(object sender, RoutedEventArgs e)
{
    textbox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    textbox2.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}

or, you can implement IDataErrorInfo and update your Text binding so that it ValidatesOnDataErrors 或者,您可以实现IDataErrorInfo并更新您的Text绑定,以便其ValidatesOnDataErrors

 <Binding Path="Entity.LastName" NotifyOnValidationError="True" ValidatesOnDataErrors="True">

Here's a simple example on how to implement IDataErrorInfo 这是有关如何实现IDataErrorInfo的简单示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM