WPF使用IDataErrorInfo进行数据校验

这篇博客将介绍如何使用IDataErrorInfo进行数据校验。下面直接看例子。一个Customer类,两个属性(FirstName, Age)

class Customer
{
public string FirstName
{
get;
set;
} public int Age
{
get;
set;
}
}

将Customer类继承IDataErrorInfo,并实现它的属性。

    class Customer : System.ComponentModel.IDataErrorInfo
{
public string this[string columnName]
{
get
{
string result = string.Empty; if(columnName == "FirstName")
{
if(string.IsNullOrWhiteSpace(FirstName))
{
result = "Name cannot null or empty.";
}
}
else if(columnName == "Age")
{
if(Age < )
{
result = "Age cannot less then zero.";
}
} return result;
}
}
public string Error
{
get
{
return null;
}
} public string FirstName
{
get;
set;
} public int Age
{
get;
set;
}
}

在UI中绑定Customer的FirstName,Age属性,并且当出现错误数据时触发验证。

    <Window.Resources>
<local:Customer x:Key="CustomerInstance" FirstName="Sam Bent" Age="" />
<ControlTemplate x:Key="TextBoxErrorTemplate">
<Grid>
<Border BorderBrush="Blue" BorderThickness="">
<AdornedElementPlaceholder/>
</Border>
</Grid>
</ControlTemplate>
</Window.Resources>
<StackPanel Margin="">
<TextBox
Text="{Binding
Source={StaticResource CustomerInstance},
Path=FirstName,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"
ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"
Validation.ErrorTemplate="{x:Null}"

Margin="0,5" /> <TextBox Text="{Binding
Source={StaticResource CustomerInstance},
Path=Age,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"
Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>

</TextBox>
</StackPanel>

将Customer的FirstName与Age属性分别绑定在两个TextBox中,设置ValidatesOnDataErrors=True来触发验证。将错误信息绑定在TextBox的ToolTip属性上,

ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" 或者

ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"或者

<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>

另外可以对ErrorTemplate进行定制,例如上面代码中的TextBoxErrorTemplate。

运行结果:

WPF使用IDataErrorInfo进行数据校验

代码点击这里下载,感谢您的阅读。

上一篇:spring boot将jar包转换成war包发布


下一篇:centos 6.5重置Root密码