WPF CommandParameter绑定到PasswordBox.Password

lig*_*ght 6 wpf binding

我有一个MVVM运行树视图.在顶层是包含凭据的Account对象.我有一个PasswordBox,可用于更改帐户密码,后面有一个Save按钮.代码如下,是帐户级别模板的一部分:

PasswordBox Width="100" x:Name="pbPassword"/>

Button x:Name="btnSave" Command="{Binding ClickCommand}" CommandParameter="{Binding ElementName=pbPassword, Path=Password}" Height="20" Width="50">Save

PasswordBox Width="100" x:Name="pbPassword"/>

Button x:Name="btnSave" Command="{Binding ClickCommand}" CommandParameter="{Binding ElementName=pbPassword, Path=Password}" Height="20" Width="50">Save

PasswordBox Width="100" x:Name="pbPassword"/>

Button x:Name="btnSave" Command="{Binding ClickCommand}" CommandParameter="{Binding ElementName=pbPassword, Path=Password}" Height="20" Width="50">Save

我在PasswordBox中添加了一些内容,然后单击"保存".触发ClickCommand,但参数始终为string.Empty.我错过了什么?

Ben*_*udo 9

出于安全原因,WPF不提供PasswordBox(参考的密码属性的依赖属性1,2),这样你的命令参数绑定不起作用.

您可以将命令参数绑定到PasswordBox,然后从命令实现中访问相应的属性:

<Button Command="{Binding ClickCommand}" CommandParameter="{Binding ElementName=pbPassword}">

// command implementation
public void Execute(object parameter)
{
    var passwordBox = (PasswordBox)parameter;
    var value = passwordBox.Password;
}
Run Code Online (Sandbox Code Playgroud)

您可能需要考虑其他不涉及将密码作为纯文本保存在内存中的选项.

希望这有帮助,