如何在 WPF 程序中使用 IDataErrorInfo.Error?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14023552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use IDataErrorInfo.Error in a WPF program?
提问by guogangj
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;
}
}
}
Binding the PersonName and Age properties is easy:
绑定 PersonName 和 Age 属性很容易:
<TextBox Text="{Binding PersonName, ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding Age, ValidatesOnDataErrors=True}" />
However, how can I use the Error property and show it appropriately?
但是,如何使用 Error 属性并适当地显示它?
回答by Daniel Castro
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:
您应该修改 TextBox 样式,以便它显示属性有什么问题。这是一个简单的示例,将错误显示为工具提示:
<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>
Just put it inside Application.Resources from your app.xaml file and it will be aplied for every textbox of your application:
只需将它放在 app.xaml 文件中的 Application.Resources 中,它将适用于应用程序的每个文本框:
<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>
回答by CodeNaked
Here is an example, adapted from this question, that shows how to display the error in Tooltip:
这是一个改编自此问题的示例,它显示了如何在工具提示中显示错误:
<TextBox>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>