XAML 清除控件后无法重置UI中的密码框输入[已关闭]

tuwxkamq  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(122)

已关闭,该问题需要details or clarity,目前不接受回答。
**想要改进此问题?**通过editing this post添加详细信息并澄清问题。

4天前关闭。
Improve this question
有人可以建议如何清除/重置输入密码箱在简单的方式附加图像我的代码更改,直到viewmodel输入密码字段得到清除,但xaml ui它不是得到重置无法做绑定路径密码箱. x1c 0d1x

kmbjn2e3

kmbjn2e31#

您可以从PasswordBox.PasswordChanged事件处理程序中清除PasswordBox

<Window>
  <PasswordBox PasswordChanged="OnPasswordChanegd" />
</Window>
private void OnPasswordChanged(object sender, RoutedEventArgs e)
{
  var passwordBox = sender as PasswordBox;
  this.ViewModel.AuthenticateUser(passwordBox.SecureString);

  passwordBox.SecureString.Dispose();

  // Clear the password box
  passwordBox.Clear();
}

或者,让视图观察视图模型,以便在Passwordbox准备好被清除时被触发。

ViewModel.cs

class ViewModel : INotifyPropertyChanged
{
  public event EventHandler Authenticated;

  private bool isAuthenticationSuccessful 
  public bool IsAuthenticationSuccessful 
  {
    get => this.isAuthenticationSuccessful;
    private set
    {
      this.isAuthenticationSuccessful = value;
      OnPropertyChanged();
      OnAuthenticated();
    }
  }

  public void AuthenticateUser(SecureString clientPassword)
  {
    // TODO::Validate credentials
    this.IsAuthenticationSuccessful = ?;
  }

  private void OnAuthenticated()
    => this.Authenticated?.Invoke(this, EventArgs.Empty);
}

MainWindow.xaml.cs

class MainWindow : Window
{
  public MainWindow()
  {
    var viewModel = new ViewModel();
    viewModel.Authenticated += OnAuthenticated;

    this.DataContext = viewModel;
  }

  private void OnPasswordChanged(object sender, RoutedEventArgs e)
  {
    var passwordBox = sender as PasswordBox;
    this.ViewModel.AuthenticateUser(passwordBox.SecureString);
  }

  private void OnAuthenticated(object sender, EventArgs e)
  {    
    var viewModel = sender as ViewModel;
    viewModel.Authenticated -= OnAuthenticated;
    this.PasswordBox.SecureString.Dispose();
    this.PasswordBox.Clear();
  }
}

相关问题