简体   繁体   English

如何验证PasswordBox WPF

[英]How to validate PasswordBox WPF

I'm trying to make a validation for a PasswordBox . 我正在尝试对PasswordBox进行验证。 For making validations I followed this link , that shows how to validate on TextBox . 为了进行验证,我按照此链接显示了如何在TextBox上进行验证。

The problem comes with PasswordBoxes . PasswordBoxes带来了问题。 Because its Password is not bindable due to security reasons, I tried to make a binding following this link (also explained here , for CodeProject users). 由于安全原因,其Password不可绑定,因此我尝试在此链接之后进行绑定( 此处也为CodeProject用户进行了说明)。

So, apparently, fantastic! 所以,显然,太棒了! I can bind my PasswordBox with its Password property, so then I can bind with my validation. 我可以使用Password属性绑定我的PasswordBox ,然后我可以绑定我的验证。 But it ignores me... 但它忽略了我......

This is a regular TextBox that I use and works fine: 这是我使用的常规TextBox并且工作正常:

<local:ErrorProvider Grid.Column="1" Grid.Row="2" >
    <TextBox Width="160" 
          HorizontalAlignment="Left" 
           Name="textBoxUserPass" 
           Text="{Binding Path=Password, UpdateSourceTrigger=Explicit}" />
 </local:ErrorProvider>

And this is the PasswordBox I tried to simulate: 这是我试图模拟的PasswordBox

<local:ErrorProvider Grid.Column="1" Grid.Row="2" >
      <PasswordBox Width="160"
          HorizontalAlignment="Left"
          Name="textBoxUserPass"
          local:PasswordBoxAssistant.BindPassword="True"
          local:PasswordBoxAssistant.BoundPassword="{Binding Path=Password, UpdateSourceTrigger=Explicit}" />
 </local:ErrorProvider>

This is how I get the BindingExpression for each TextBox : 这就是我为每个TextBox获取BindingExpression的方法:

BindingExpression beUserName = textBoxUserName.GetBindingExpression(TextBox.TextProperty);
if (beUserName != null) beUserName.UpdateSource();

And this is how I get it for the PasswordBox : 这就是我为PasswordBox获取它的方法:

BindingExpression bePassword = textBoxUserPass.GetBindingExpression(PasswordBoxAssistant.BoundPassword);
if (bePassword != null) bePassword.UpdateSource();

If we made any mistake (defined on my Validation class), when I do this: 如果我们犯了任何错误(在我的Validation类中定义),当我这样做时:

if (!beUserName.HasError && !bePassword.HasError)

each BindingExpression should say true of false depending on error validations. 每个BindingExpression应该说取决于错误验证的事实 But for my PasswordBox never gets the value... Any idea? 但是对于我的PasswordBox永远不会得到价值......任何想法?

Try setting ValidatesOnDataErrors=True and ValidatesOnExceptions=True on your binding: 尝试在绑定上设置ValidatesOnDataErrors=TrueValidatesOnExceptions=True

<PasswordBox ...
   local:PasswordBoxAssistant.BoundPassword="{Binding Path=Password,
      UpdateSourceTrigger=Explicit, 
      ValidatesOnDataErrors=True, 
      ValidatesOnExceptions=True}"
/>

Set Mode=TwoWay on your binding 在绑定上设置Mode = TwoWay

local:PasswordBoxAssistant.BoundPassword="{Binding Path=Password,Mode=TwoWay,
UpdateSourceTrigger=Explicit}"

Another solution, without using any "unsecure" string in the middle, is to adapt the Window code, something like this: 另一种解决方案是在中间没有使用任何“不安全”字符串,而是调整Window代码,如下所示:

Let's suppose I have an MVVM object like this, with WPF validation using IDataErrorInfo : 假设我有一个像这样的MVVM对象,使用IDataErrorInfo进行WPF验证:

public class MyObject : INotifyPropertyChanged, IDataErrorInfo
{
    ...
    public SecureString SecurePassword
    {
        get
        { ... }
        set
        {
            ...
            OnPropertyChanged("SecurePassword");
        }
    }

    ...

    string IDataErrorInfo.Error { get { return Validate(null); } }
    string IDataErrorInfo.this[string columnName] { get { return Validate(columnName); } }

    private string Validate(string memberName)
    {
        string error = null;
        ...
        if (memberName == "SecurePassword" || memberName == null)
        {
            // this is where I code my custom business rule
            if (SecurePassword == null || SecurePassword.Length == 0)
            {
                error = "Password must be specified.";
            }
        }
        ...
        return error;
    }

}

And a Window Xaml with a PasswordBox like this: 还有一个带有PasswordBox的Window Xaml,如下所示:

<PasswordBox Name="MyPassword" PasswordChanged="MyPassword_Changed" ... />

Then, the corresponding Window code like this will trigger PasswordBox binding: 然后,像这样的相应Window代码将触发PasswordBox绑定:

// add a custom DependencyProperty
public static readonly DependencyProperty SecurePasswordProperty =
    DependencyProperty.RegisterAttached("SecurePassword", typeof(SecureString), typeof(MyWindow));

public MyWindow()
{
    InitializeComponent();

    DataContext = myObject; // created somewhere

    // create a binding by code
    Binding passwordBinding = new Binding(SecurePasswordProperty.Name);
    passwordBinding.Source = myObject;
    passwordBinding.ValidatesOnDataErrors = true;
    // you can configure other binding stuff here
    MyPassword.SetBinding(SecurePasswordProperty, passwordBinding);
}

private void MyPassword_Changed(object sender, RoutedEventArgs e)
{
    // this should trigger binding and therefore validation
    ((MyObject)DataContext).SecurePassword = MyPassword.SecurePassword;
}

As far as I remember, the only way to add validation on a PasswordBox is to throw a new ValidationException in the setter of the binding property for SecurePassword. 据我所知,在PasswordBox上添加验证的唯一方法是在SecurePassword的绑定属性的setter中抛出一个新的ValidationException。 The PasswordBoxAssistant will not help you with this. PasswordBoxAssistant对此没有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM