如何在WPF程序中使用IDataErrorInfo.Error? [英] How to use IDataErrorInfo.Error in a WPF program?
本文介绍了如何在WPF程序中使用IDataErrorInfo.Error?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的对象:
I have an object like that:
public class Person : IDataErrorInfo
{
public string PersonName{get;set;}
public int Age{get;set;}
string IDataErrorInfo.this[string propertyName]
{
get
{
if(propertyName=="PersonName")
{
if(PersonName.Length>30 || PersonName.Length<1)
{
return "Name is required and less than 30 characters.";
}
}
return null;
}
}
string IDataErrorInfo.Error
{
get
{
if(PersonName=="Tom" && Age!=30)
{
return "Tom must be 30.";
}
return null;
}
}
}
绑定PersonName和Age属性很容易:
Binding the PersonName and Age properties is easy:
<TextBox Text="{Binding PersonName, ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding Age, ValidatesOnDataErrors=True}" />
但是,如何使用Error属性并正确显示它?
However, how can I use the Error property and show it appropriately?
推荐答案
您应该修改TextBox样式,以显示该属性出了什么问题.这是一个简单的示例,将错误显示为工具提示:
You should modify the TextBox style so it shows what's wrong with the property. Here is a simple example that shows the error as tooltip:
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors).CurrentItem.ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
只需将其放入来自您的app.xaml文件的Application.Resources中,它将被添加到您应用程序的每个文本框中:
Just put it inside Application.Resources from your app.xaml file and it will be aplied for every textbox of your application:
<Application.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors).CurrentItem.ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Application.Resources>
这篇关于如何在WPF程序中使用IDataErrorInfo.Error?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文