为了避免密码在内存中作为纯文本在任何时候都可用,我将值作为参数提供给我的命令。
<Label>User Name</Label>
<TextBox Text="{Binding UserName}" />
<Label>Password</Label>
<PasswordBox Name="PasswordBox" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0 16 0 0">
<Button Margin="0 0 8 0" MinWidth="65"
Command="{Binding LoginAccept}"
CommandParameter="{Binding ElementName=PasswordBox}">
Login
</Button>
<Button MinWidth="65" Command="{Binding LoginCancel}">Cancel</Button>
</StackPanel>
然后在我的视图模型中。
public DelegateCommand<object> LoginAccept { get; private set; }
public DelegateCommand<object> LoginCancel { get; private set; }
public LoginViewModel {
LoginAccept = new DelegateCommand<object>(o => OnLogin(o), (o) => IsLoginVisible);
LoginCancel = new DelegateCommand<object>(o => OnLoginCancel(), (o) => IsLoginVisible);
}
private void OnLogin(object o)
{
var passwordBox = (o as System.Windows.Controls.PasswordBox);
var password = passwordBox.SecurePassword.Copy();
passwordBox.Clear();
ShowLogin = false;
var credential = new System.Net.NetworkCredential(UserName, password);
}
private void OnLoginCancel()
{
ShowLogin = false;
}
虽然直接从绑定中提供 SecurePassword 是有意义的,但它似乎总是提供一个空值。所以这不起作用:
<Button Margin="0 0 8 0" MinWidth="65"
Command="{Binding LoginAccept}"
CommandParameter="{Binding ElementName=PasswordBox, Path=SecurePassword}">