Jat*_*tin 13 validation wpf idataerrorinfo wpf-4.0
我正在尝试使用IDataErrorInfo验证我的模型类,如下所示.
//Validators
public string this[string propertyName] {
get {
string error = null;
if (propertyName == "Name") {
error = ValidateName();
}
return error;
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但视图首次加载时已经包含验证错误.首次加载视图时是否可以忽略/禁止验证错误.此外,通常的做法是在视图加载时以及在用户启动模型属性的数据条目之前显示错误.
问候,Nirvan.
编辑: 这是我设置IDataErrorInfo的方式.
<TextBox Text="{Binding Name, ValidatesOnDataErrors=True}" Grid.Row="1" Grid.Column="1" />
Run Code Online (Sandbox Code Playgroud)
我采取了以下方法并且有效。基本上,模型应该正确记录错误并将它们列在字典中,即使对象刚刚实例化并且用户尚未输入任何文本。所以我没有更改我的模型代码或 IDataErrorInfo 验证代码。相反,我最初只是将 Validation.Error Template 属性设置为 {x:Null}。然后有代码连接 TextBox 的 LostFocus 事件,将 Validation.Error 模板更改回我正在使用的模板。为了实现模板交换并将 LostFocus 事件处理程序附加到应用程序中的所有 TextBox,我使用了几个依赖属性。这是我使用过的代码。
依赖属性和 LostFocus 代码:
public static DependencyProperty IsDirtyEnabledProperty = DependencyProperty.RegisterAttached("IsDirtyEnabled",
typeof(bool), typeof(TextBoxExtensions), new PropertyMetadata(false, OnIsDirtyEnabledChanged));
public static bool GetIsDirtyEnabled(TextBox target) {return (bool)target.GetValue(IsDirtyEnabledProperty);}
public static void SetIsDirtyEnabled(TextBox target, bool value) {target.SetValue(IsDirtyEnabledProperty, value);}
public static DependencyProperty ShowErrorTemplateProperty = DependencyProperty.RegisterAttached("ShowErrorTemplate",
typeof(bool), typeof(TextBoxExtensions), new PropertyMetadata(false));
public static bool GetShowErrorTemplate(TextBox target) { return (bool)target.GetValue(ShowErrorTemplateProperty); }
public static void SetShowErrorTemplate(TextBox target, bool value) { target.SetValue(ShowErrorTemplateProperty, value); }
private static void OnIsDirtyEnabledChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) {
TextBox textBox = (TextBox)dependencyObject;
if (textBox != null) {
textBox.LostFocus += (s, e) => {
if ((bool) textBox.GetValue(ShowErrorTemplateProperty) == false) {
textBox.SetValue(ShowErrorTemplateProperty, true);
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
如果 IsDirtyEnabled 依赖属性设置为 true,它将使用回调将 TextBox 的 LostFocus 事件附加到处理程序。处理程序只是将 ShowErrorTemplate 附加属性更改为 true,这会在 TextBox 失去焦点时触发文本框的样式触发器以显示 Validation.Error 模板。
文本框样式:
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate" Value="{StaticResource ValidationErrorTemplate}"/>
<Setter Property="gs:TextBoxExtensions.IsDirtyEnabled" Value="True" />
<Style.Triggers>
<Trigger Property="gs:TextBoxExtensions.ShowErrorTemplate" Value="false">
<Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
</Trigger>
</Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)
对于一个简单的事情来说,这似乎代码太多,但是我只需为我正在使用的所有文本框执行一次。
问候,涅槃。