WPF:验证确认密码密码、WPF

2023-09-05 01:41:15 作者:自衬

我有2 PasswordBoxes。我需要检查的密码相同。我不想写这个条件为[] .xaml.cs code,但我想以红色标记PasswordBox时的密码是不相等的。

I have 2 PasswordBoxes. I need to check are passwords equal. I don't want to write this condition into [].xaml.cs code, but i want to mark PasswordBox in red when passwords aren't equal.

我应该写特别的有效性规则,一些code。在视图模型还是其他什么东西?谁能帮助我?现在,验证上写的是[] .xaml.cs,但我想,以避免它。

Should i write special ValidationRule, some code in ViewModel or something else? Can anyone help me? Now the validation is written in the [].xaml.cs but i want to avoid it.

推荐答案

使用:

<PasswordBox Name="tbPassword" />
<PasswordBox Name="tbPasswordConf" />
<PasswordValidator 
      Box1="{Binding ElementName=tbPassword}" 
      Box2="{Binding ElementName=tbPasswordConf}" />

code(这code未涵盖所有情况下):

Code (this code is not cover all cases):

public class PasswordValidator : FrameworkElement
 {
  static IDictionary<PasswordBox, Brush> _passwordBoxes = new Dictionary<PasswordBox, Brush>();

  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。

Also, it's possible to define dependency property with style of error and setting it instead of BorderBrush. But i don't know how to use in this case the standard ErrorTemplate.

 
精彩推荐