Guest User

Untitled

a guest
Jan 18th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. <Window.Resources>
  2. <BooleanToVisibilityConverter x:Key="VisibilityConverter" />
  3. </Window.Resources>
  4.  
  5. <StackPanel>
  6. <Grid>
  7. <TextBox
  8. Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}"
  9. />
  10. <PasswordBox
  11. x:Name="PasswordBox"
  12. PasswordChanged="OnPasswordChanged"
  13. Visibility="{Binding HidePassword, Converter={StaticResource VisibilityConverter}}"
  14. />
  15. </Grid>
  16. <CheckBox
  17. Content="Show password"
  18. IsChecked="{Binding ShowPassword}"
  19. />
  20. </StackPanel>
  21.  
  22. public class ViewModel : ViewModelBase
  23. {
  24. private string _password;
  25. public string Password
  26. {
  27. get => _password;
  28. set => Set(ref _password, value);
  29. }
  30.  
  31. private bool _showPassword;
  32. public bool ShowPassword
  33. {
  34. get => _showPassword;
  35. set
  36. {
  37. Set(ref _showPassword, value);
  38. RaisePropertyChanged(nameof(HidePassword));
  39. }
  40. }
  41.  
  42. public bool HidePassword => !ShowPassword;
  43. }
  44.  
  45. public partial class MainWindow : Window
  46. {
  47. public MainWindow()
  48. {
  49. InitializeComponent();
  50. InitializeViewModel();
  51. }
  52.  
  53. public ViewModel ViewModel => DataContext as ViewModel;
  54.  
  55. private void InitializeViewModel()
  56. {
  57. DataContext = new ViewModel();
  58.  
  59. ViewModel.PropertyChanged += (sender, args) =>
  60. {
  61. // Update the password box only when it's not visible;
  62. // otherwise, the cursor goes to the beginning on each keystroke
  63. if (!PasswordBox.IsVisible)
  64. {
  65. if (args.PropertyName == nameof(ViewModel.Password))
  66. PasswordBox.Password = ViewModel.Password;
  67. }
  68. };
  69. }
  70.  
  71. private void OnPasswordChanged(object sender, RoutedEventArgs e)
  72. {
  73. ViewModel.Password = PasswordBox.Password;
  74. }
  75. }
Add Comment
Please, Sign In to add comment