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.
谢谢你。
1 个解决方案
#1
-1
You can force the rules to update automatically once the Window has bee loaded so that the blank fields will indicate an error:
当窗口加载bee时,您可以强制规则自动更新,以便空白字段将指示错误:
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并更新文本绑定,以便它验证ondataerrors
<Binding Path="Entity.LastName" NotifyOnValidationError="True" ValidatesOnDataErrors="True">
Here's a simple example on how to implement IDataErrorInfo
下面是一个如何实现IDataErrorInfo的简单示例
#1
-1
You can force the rules to update automatically once the Window has bee loaded so that the blank fields will indicate an error:
当窗口加载bee时,您可以强制规则自动更新,以便空白字段将指示错误:
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并更新文本绑定,以便它验证ondataerrors
<Binding Path="Entity.LastName" NotifyOnValidationError="True" ValidatesOnDataErrors="True">
Here's a simple example on how to implement IDataErrorInfo
下面是一个如何实现IDataErrorInfo的简单示例