WPF:validation确认密码

我有2个PasswordBoxes。 我需要检查密码是否相等。 我不想将这个条件写入[] .xaml.cs代码,但我想在密码不相等时将PasswordBox标记为红色。

我应该编写特殊的ValidationRule,ViewModel中的一些代码还是别的什么? 谁能帮我? 现在validation写在[] .xaml.cs中,但我想避免它。

使用:

   

代码(此代码不涵盖所有情况):

 public class PasswordValidator : FrameworkElement { static IDictionary _passwordBoxes = new Dictionary(); public static readonly DependencyProperty Box1Property = DependencyProperty.Register("Box1", typeof(PasswordBox), typeof(PasswordValidator), new PropertyMetadata(Box1Changed)); public static readonly DependencyProperty Box2Property = DependencyProperty.Register("Box2", typeof(PasswordBox), typeof(PasswordValidator), new PropertyMetadata(Box2Changed)); public PasswordBox Box1 { get { return (PasswordBox)GetValue(Box1Property); } set { SetValue(Box1Property, value); } } public PasswordBox Box2 { get { return (PasswordBox)GetValue(Box2Property); } set { SetValue(Box2Property, value); } } private static void Box1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { } private static void Box2Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { var pv = (PasswordValidator)d; _passwordBoxes[pv.Box2] = pv.Box2.BorderBrush; pv.Box2.LostFocus += (obj, evt) => { if (pv.Box1.Password != pv.Box2.Password) { pv.Box2.BorderBrush = new SolidColorBrush(Colors.Red); } else { pv.Box2.BorderBrush = _passwordBoxes[pv.Box2]; } }; } } 

此外,可以使用错误样式定义依赖项属性并设置它而不是BorderBrush。 但我不知道在这种情况下如何使用标准的ErrorTemplate。

在viewModel中创建一个只读属性,并返回PasswordConfirmBox边框的画笔,然后将文本框绑定到属性

收到评论后编辑我没有测试过这个并且可能会有一些小错误但是这样你可以根据转换器参数返回不同的类型

  public bool PasswordValidation { get { if (textBox1.Text == textBox2.Text) return true; else return false; } } 

价值转换器:

  public class ValConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (parameter == "") { if ((value as bool?) ?? false) return Visibility.Hidden; else return Visibility.Visible; } else if (parameter == "") { if ((value as bool?) ?? false) return new SolidColorBrush(Colors.Black); else return new SolidColorBrush(Colors.Red); } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (parameter == "Visibility") { if ((System.Windows.Visibility)value == Visibility.Visible) return false; else return true; } else if (parameter == "Brush") { if (((SolidColorBrush)value).Color == Colors.Black) return true; else return false; } } 

XAML: