/// <summary> /// 自定义设置抛出验证不通过的信息 /// </summary> /// <param name="frameworkElement">控件自身</param> /// <param name="message">验证不通过的信息</param> /// <param name="viewmodel">当前控件所属的ViewModel</param> /// <param name="container">当前控件所属的容器:Grid,StackPanel</param> /// <param name="needClearErrorWhenLostFocus">当再一次失去焦点时是否需要清除掉验证错误信息</param> public static void Validation(this FrameworkElement frameworkElement, string message, ModelBase viewmodel, FrameworkElement container, bool needClearErrorWhenLostFocus) { frameworkElement.SetValidation(message); frameworkElement.RaiseValidationError(); if (needClearErrorWhenLostFocus) { TagObject tag = new TagObject(); tag.ViewModel = viewmodel; tag.Container = container; frameworkElement.Tag = tag; frameworkElement.LostFocus += new RoutedEventHandler(frameworkElement_LostFocus); } }
static void frameworkElement_LostFocus(object sender, RoutedEventArgs e) { TagObject tag = null; FrameworkElement frameworkElement = sender as FrameworkElement; if (frameworkElement.Tag != null) { tag = frameworkElement.Tag as TagObject; } if (tag == null) { return; } ValidationManager.Validate(tag.Container); if (!tag.ViewModel.HasValidationErrors) { frameworkElement.ClearValidationError(); } }