我采用了以下方法并且它有效。基本上,即使对象只是实例化而用户还没有输入任何文本,Model应该记录错误并将其列在字典中。因此我没有更改我的Model代码或IDataErrorInfo验证代码。相反,我只是最初将Validation.ErrorTemplate属性设置为{x:Null}。然后有一些代码来连接TextBox的LostFocus事件,将Validation.ErrorTemplate模板更改回我正在使用的内容。为了实现模板交换和将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);
}
};
}
}
如果IsDirtyEnabled依赖属性设置为true,则使用回调将TextBox的LostFocus事件附加到处理程序。 处理程序只是将ShowErrorTemplate附加属性更改为true,这反过来触发文本框的样式触发器以显示Validation.Error模板,当TextBox失去焦点时。
TextBox样式:
<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>
这可能看起来是为了一个简单的事情而过于冗长,但我只需要这样做一次,就可以应用到所有我使用的文本框中。
问候,
Nirvan。