C#C
C#11mo ago
WizzyWodich

PasswordBox how to pass data to viewModel

This is a piece of code from View:

        private void PasswordInput_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (DataContext is RegistrationVM vm && sender is PasswordBox passwordBox)
            {
                vm.Password = passwordBox.SecurePassword;
                MessageBox.Show($"Password {passwordBox.SecurePassword} | {passwordBox.Password}");
            }
        }



This is a piece of code from ViewModel:

public ICommand RegisterCommand { get; }

private async Task Register()
{
    if (IsPasswordValid())
    {
        string password = ConvertSecureStringToString(Password);
        bool success = await _tcpClientService.RegisterAsync(UserLogin, password);
        if (success)
        {
            MessageBox.Show("Регистрация успешна!");
            NavigateToLogin();
        }
        else
        {
            MessageBox.Show("Ошибка регистрации!");
        }
    }
    else
    {
        MessageBox.Show("Пароли не совпадают или слишком короткие!");
    }
}

private string ConvertSecureStringToString(SecureString secureString)
{
    IntPtr unmanagedString = IntPtr.Zero;
    try
    {
        unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
        return Marshal.PtrToStringUni(unmanagedString);
    }
    finally
    {
        if (unmanagedString != IntPtr.Zero)
        {
            Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
        }
    }
}
Was this page helpful?