首先要确保已经安装了这个dll
xaml:
<UserControl x:Class="MyWpf.MyValid" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MyWpf.CommonService" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <i:Interaction.Behaviors> <local:ValidationException></local:ValidationException> </i:Interaction.Behaviors> <Grid> <StackPanel> <TextBox Width="200" Margin="0 20 0 0" Height="30"> <TextBox.Text> <!-- 绑定后台Name属性,UpdateSourceTrigger="PropertyChanged"表示当属性改变的时候就立即传递到源,而不是焦点离开的时候--> <Binding Path="Name" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:NotEmptyValidationRule></local:NotEmptyValidationRule> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> <Button Content="提交" Width="200" Height="30" Margin="0 20 0 0" Command="{Binding SaveCommand}"></Button> </StackPanel> </Grid> </UserControl>
后台:
/// <summary> /// MyValid.xaml 的交互逻辑 /// </summary> public partial class MyValid : UserControl { public MyValid() { InitializeComponent(); this.DataContext = new MainViewModel(); } }
MainViewModel(安装mvvmlight.dll的时候自动生成的类,里面的内容需要根据实际情况改写):
public class MainViewModel : ViewModelBase, IValidationException { public MainViewModel() { SaveCommand = new RelayCommand(() => { if (!IsValid) { //如果验证未通过,则提示 MessageBox.Show("验证未通过"); return; } }); } //命令必须是public public RelayCommand SaveCommand { get; set; } private bool isValid; public bool IsValid { get { return isValid; } set { isValid = value; RaisePropertyChanged(); } } private string name; public string Name { get { return name; } set { name = value; } } }
验证器:
namespace MyWpf.CommonService { public interface IValidationException { bool IsValid { get; set; } } public class ValidationException : Behavior<FrameworkElement> { //错误次数 等于0表示没有错误 private int _count = 0; protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.AddHandler(Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(OnValidationError)); } private void OnValidationError(object sender, ValidationErrorEventArgs e) { IValidationException handler = null; if (AssociatedObject.DataContext is IValidationException) { handler = this.AssociatedObject.DataContext as IValidationException; } if (handler == null) { return; } var element = e.OriginalSource as UIElement; if (element == null) return; if (e.Action == ValidationErrorEventAction.Added) { _count++; } else if (e.Action == ValidationErrorEventAction.Removed) { _count--; } handler.IsValid = _count == 0; } /// <summary> /// 解除关联的事件 /// </summary> protected override void OnDetaching() { base.OnDetaching(); //AssociatedObject.MouseMove -= AssociatedObject_MouseMove; //AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave; } } /// <summary> /// 实现一个不可为空的验证器 /// </summary> public class NotEmptyValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { return string.IsNullOrWhiteSpace((value ?? "").ToString()) ? new ValidationResult(false, "Error") : ValidationResult.ValidResult; } } }
结果:
NotifyOnValidationError="True"
如果在源更新过程中出现验证错误时应对绑定对象引发 System.Windows.Controls.Validation.Error 附加事件,则为 true;否则为