<Window.Resources>
<!--数据源-->
<local:Person Age="100" Name="Tom" x:Key="Data"></local:Person>
<!--TextBox模板-->
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<!--验证触发-->
<Trigger Property="Validation.HasError" Value="True">
<!--错误信息模板-->
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<Border Background="Red" DockPanel.Dock="Right" Margin="5,0,0,0"
Width="20" Height="20" CornerRadius="20"
ToolTip="{Binding ElementName=customAdorner,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
<TextBlock Text="*" VerticalAlignment="Center" HorizontalAlignment="Center"
FontWeight="Bold" Foreground="White"/>
</Border>
<!--占位,表示修饰控件相对于ControlTemplate中其它元素所放置的位置(这个示例中用于文本框的占位)-->
<AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center">
<Border BorderBrush="Red" BorderThickness="1"></Border>
</AdornedElementPlaceholder>
</DockPanel></ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Height="35" Width="120"
Text="{Binding Source={StaticResource Data},Path=Age,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True,ValidatesOnExceptions=True,
NotifyOnValidationError=True}" />
</Grid>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;namespace WpfCommand.Models
{
public class Person:INotifyPropertyChanged,IDataErrorInfo
{private string _name;
public string Name
{
get { return _name; }
set {
_name = value;
RaisePropertyChanged("Name");
}
}
private int _age;
// [Range] ValidationAttribute:(需要添加 System.ComponentModel.DataAnnotations.dll)
[Range(19,99,ErrorMessage="未成年")]
public int Age
{
get { return _age; }
set {
_age = value;
RaisePropertyChanged("Age");
}
}public string Error { get { return ""; } }
//索引器
public string this[string ColumnName]
{
get {
var vc = new ValidationContext(this, null, null);
vc.MemberName = ColumnName;
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(this.GetType().GetProperty(ColumnName).GetValue(this, null), vc, res);
if (res.Count > 0)
{
return string.Join(Environment.NewLine,res.Select(r=>r.ErrorMessage).ToArray());
}
return string.Empty;
}}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}}
}
}
【WPF】验证,码迷,mamicode.com