c# - WPF 重复密码 IMultiValueConverter

标签 c# wpf multibinding passwordbox imultivalueconverter

我想要一个密码框和另一个密码框来重复所选的密码和提交按钮。

这就是我得到的:

WPF:

<UserControl.Resources>
    <converter:PasswordConverter x:Key="PasswdConv"/>
</UserControl.Resources>


<PasswordBox PasswordChar="*" Name="pb1"/>
<PasswordBox PasswordChar="*" Name="pb2"/>
<Button Content="Submit" Command="{Binding ChangePassword}">
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource PasswdConv}">
            <MultiBinding.Bindings>
                <Binding ElementName="pb1"/>
                <Binding ElementName="pb2"/>
            </MultiBinding.Bindings>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

转换器:

public class PasswordConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        List<string> s = values.ToList().ConvertAll(p => SHA512(((PasswordBox)p).Password));
        if (s[0] == s[1])
            return s[0];
        return "|NOMATCH|";
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

命令(更改密码):

if ((p as string) != "|NOMATCH|")
{
    MessageBox.Show("Password changed");
}
else
{
    MessageBox.Show("Passwords not matching");
}

当我在转换器和命令中设置断点时,我得到以下结果: 一旦 View 加载,它就会跳入转换器并尝试转换两个密码框。两者都是空的。 当我按下按钮(两个密码框中的内容无关紧要)时,它不会进入转换器并在命令 if 处停止。 P代表空密码。

最佳答案

仅当多重绑定(bind)的源属性更改时才会调用 Convert 方法,但您绑定(bind)到 PasswordBox 本身并且它永远不会更改。

绑定(bind)到 Password 属性也不起作用,因为当该属性更改时 PasswordoBox 不会引发更改通知。

它确实会引发 PasswordChanged 事件,因此您可以处理此事件并在此事件处理程序中设置 CommandParameter 属性,而不是使用转换器:

private void OnPasswordChanged(object sender, RoutedEventArgs e)
{
    string password = "|NOMATCH|";
    List<PasswordBox> pb = new List<PasswordBox>(2) { };
    List<string> s = new List<string>[2] { SHA512(pb1.Password), SHA512(pb2.Password) };
    if (s[0] == s[1])
        password = s[0];

    btn.CommandParameter = password;
}

XAML:

<PasswordBox PasswordChar="*" Name="pb1" PasswordChanged="OnPasswordChanged"/>
<PasswordBox PasswordChar="*" Name="pb2" PasswordChanged="OnPasswordChanged"/>
<Button x:Name="btn" Content="Submit" Command="{Binding ChangePassword}" />

如果您希望能够在多个 View 和 PasswordBox 控件中重用此功能,您应该编写 attached behaviour .

关于c# - WPF 重复密码 IMultiValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51920617/

相关文章:

c# - 检查应用程序是否安装在注册表中

c# - Binding 的构造函数中的参数 formattingEnabled 有什么作用?

c# - CS0120 : An object reference is required

c# - 为什么无法获取已启动进程的主窗口句柄?

c# - 在 WPF DataGrid 中保留用户定义的排序顺序

c# - 格式化 MultiBinding TimeSpan 以隐藏毫秒

c# - LINQ 在选择匿名类型时包含嵌套属性

wpf - 如何在 XAML 中使用文字大括号 "{"?

c# - 无法使用多重绑定(bind)绑定(bind) DataGrid ItemsSource - 简单绑定(bind)工作正常

c# - WPF CommandParameter MultiBinding 值为 null