您可以讓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