Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <Window.Resources>
- <BooleanToVisibilityConverter x:Key="VisibilityConverter" />
- </Window.Resources>
- <StackPanel>
- <Grid>
- <TextBox
- Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}"
- />
- <PasswordBox
- x:Name="PasswordBox"
- PasswordChanged="OnPasswordChanged"
- Visibility="{Binding HidePassword, Converter={StaticResource VisibilityConverter}}"
- />
- </Grid>
- <CheckBox
- Content="Show password"
- IsChecked="{Binding ShowPassword}"
- />
- </StackPanel>
- public class ViewModel : ViewModelBase
- {
- private string _password;
- public string Password
- {
- get => _password;
- set => Set(ref _password, value);
- }
- private bool _showPassword;
- public bool ShowPassword
- {
- get => _showPassword;
- set
- {
- Set(ref _showPassword, value);
- RaisePropertyChanged(nameof(HidePassword));
- }
- }
- public bool HidePassword => !ShowPassword;
- }
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- InitializeViewModel();
- }
- public ViewModel ViewModel => DataContext as ViewModel;
- private void InitializeViewModel()
- {
- DataContext = new ViewModel();
- ViewModel.PropertyChanged += (sender, args) =>
- {
- // Update the password box only when it's not visible;
- // otherwise, the cursor goes to the beginning on each keystroke
- if (!PasswordBox.IsVisible)
- {
- if (args.PropertyName == nameof(ViewModel.Password))
- PasswordBox.Password = ViewModel.Password;
- }
- };
- }
- private void OnPasswordChanged(object sender, RoutedEventArgs e)
- {
- ViewModel.Password = PasswordBox.Password;
- }
- }
Add Comment
Please, Sign In to add comment