您可以让PasswordBox的此行为在MVVM中启用绑定。
PasswordBoxBehavior.cs
public class PasswordBoxBehavior : Behavior<PasswordBox>
{
public bool ResetPassword
{
get { return (bool)GetValue(ResetPasswordProperty); }
set { SetValue(ResetPasswordProperty, value); }
}
// Using a DependencyProperty as the backing store for ResetPassword. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ResetPasswordProperty =
DependencyProperty.Register("ResetPassword", typeof(bool), typeof(PasswordBoxBehavior), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnResetPasswordChanged));
static void OnResetPasswordChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
PasswordBoxBehavior behavior = depObj as PasswordBoxBehavior;
PasswordBox item = behavior.AssociatedObject as PasswordBox;
if (item == null)
return;
if ((bool)e.NewValue)
item.Password = string.Empty;
behavior.ResetPassword = false;
}
private bool isRoutedEventHandlerAssign;
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(PasswordBoxBehavior), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnTextChanged));
static void OnTextChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
PasswordBoxBehavior behavior = depObj as PasswordBoxBehavior;
PasswordBox item = behavior.AssociatedObject as PasswordBox;
if (item == null)
return;
if (item.Password != e.NewValue as string)
{
item.Password = e.NewValue as string;
}
if (!behavior.isRoutedEventHandlerAssign)
{
item.PasswordChanged += (sender, eArg) =>
{
behavior.Text = item.Password;
};
behavior.isRoutedEventHandlerAssign = true;
}
}
public PasswordBoxBehavior()
{
}
}
使用
<PasswordBox>
<i:Interaction.Behaviors>
<bh:PasswordBoxBehavior
Text="{Binding UserPassword}"
ResetPassword="{Binding IsResetPassword}" />
</i:Interaction.Behaviors>
</PasswordBox>
其中
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:bh="clr-namespace:<some namespace>;assembly=<some assembly>"
@ faflo10:是的,我分离了视图,视图模型和模型,但当然可以打破这些规则,如果绝对需要。从密码箱中读取的密码保存在我的模型中,而密码箱位于视图 – 537mfb
您可以从文件中读取并编写代码,说明'PasswordBox.Password =“ReadPassword”;' –
' PasswordBox'并不适合'MVVM',但您可以编写附加行为来设置['PasswordBox.SecurePassword'](https://msdn.microsoft.com/en-us/library/system.windows.controls.passwordbox .securepassword.aspx)(这是'SecureString')。这种行为必须能够访问现有的密码(在某些User类中也是'SecureString'),或者输入一些* fake *密码(但是你可以简单地使用'PasswordBox.Password')。 'User.IsLogged'已设置。 – Sinatr