WPF - Passwordbox input not updating

Dmtr_Grms 331 Reputation points
2022-06-10T08:39:13.36+00:00

Hi,
I'm creating a small WPF app (Visual Studio 2022, WPF , .Net 6.0, XAML-C# 10 and SQL Server), but having some trouble with the PasswordBox in Update.

Context:
I created a page containing a Datagrid with all records from my Table (CollectionView) and a Tabcontrol.
The TabControl has 2 TabItems.
First TabItem for record creation - ADD with a PasswordBox ----> it works Password field is filled with the Input Value
The Second TabItem is for record modification - Update ---> it works for all fields EXCEPT PasswordBox.

I know that the standard Control makes that is not possible to BIND the PasswordBox to my password field, but what should I do if I want to change it? Anyone knows how to solve it?

Thanks in advance

XAML Code extract:
<TabControl x:Name="TblUserdetail" HorizontalAlignment="Left" Height="231" Margin="42,430,0,0" VerticalAlignment="Top" Width="1139">
<TabItem Header="Modifica" FontWeight="Bold">
<Grid>
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFDE7E13"/>
<GradientStop Color="#FF321966" Offset="1"/>
</LinearGradientBrush>
</Grid.Background>
<Grid x:Name="GvUpdate" DataContext="{Binding ElementName=DataGridList, Path=SelectedItem}" Grid.ColumnSpan="2">
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0.6">
<GradientStop Color="#FFDE7E13"/>
<GradientStop Color="#FF321966" Offset="1"/>
</LinearGradientBrush>
</Grid.Background>
<Label x:Name="LblUserCode1" Content="Codice Utente:" HorizontalAlignment="Left" Height="25" VerticalAlignment="Top" Width="100" FontWeight="Bold" Foreground="Black"/>
<TextBox x:Name="TxtUserCode1" HorizontalAlignment="Left" Height="20" Margin="4,25,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="175" FontWeight="Normal" MaxLength="25" MaxLines="1" Text="{Binding UserCode}"/>
<Label x:Name="LblLastName1" Content="Cognome:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="0,45,0,0" Foreground="Black"/>
<TextBox x:Name="TxtLastName1" HorizontalAlignment="Left" Height="20" Margin="4,68,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="677" FontWeight="Normal" MaxLength="100" MaxLines="1" Text="{Binding LastName}" Grid.ColumnSpan="2"/>
<Label x:Name="LblFirstName1" Content="Nome:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Center" Width="100" FontWeight="Bold" Foreground="Black"/>
<TextBox x:Name="TxtFirstName1" HorizontalAlignment="Left" Height="20" Margin="4,112,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="677" FontWeight="Normal" MaxLength="100" MaxLines="1" Text="{Binding FirstName}" Grid.ColumnSpan="2"/>
<Label x:Name="LblEmail1" Content="Mail:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="4,132,0,0" Foreground="Black"/>
<TextBox x:Name="TxtEmail1" HorizontalAlignment="Left" Height="20" Margin="4,161,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="345" FontWeight="Normal" MaxLength="255" MaxLines="1" Text="{Binding Email}"/>
<Label x:Name="LblAuthLevel1" Content="Livello di Aut. :" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="433,132,0,0" Foreground="Black"/>
<TextBox x:Name="TxtAuthLevel1" HorizontalAlignment="Left" Height="18" Margin="483,161,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="18" FontWeight="Normal" MaxLength="1" MaxLines="1" Text="{Binding AuthLevel}"/>
<Label x:Name="LblPassword1" Content="Password:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Foreground="Black" Margin="756,0,0,0"/>
<PasswordBox x:Name="TxtPassword1" HorizontalAlignment="Left" Height="20" Margin="756,25,0,0" VerticalAlignment="Top" Width="250" MaxLength="32" Grid.Column="1"/>
<CheckBox x:Name="CbIsActive1" Content="Attivo" HorizontalAlignment="Left" Height="20" Margin="660,161,0,0" VerticalAlignment="Top" Width="68" FontWeight="Bold" Foreground="Black" IsChecked="{Binding IsActive}"/>
<CheckBox x:Name="CbIsDeleted1" Content="Cancellato" HorizontalAlignment="Left" Height="20" Margin="806,161,0,0" VerticalAlignment="Top" Width="100" FontWeight="Bold" Foreground="Black" IsChecked="{Binding IsDeleted}"/>
<Button x:Name="BtnUpdate1" Content="Modifica" HorizontalAlignment="Left" Height="25" Margin="1023,168,0,0" VerticalAlignment="Top" Width="100" BorderBrush="Black" FontWeight="Bold" Foreground="Black" Click="BtnUpdate1_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFFDD00"/>
<GradientStop Color="#FFFBB034" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
</Grid>
</Grid>
</TabItem>
<TabItem Header="Aggiungi" Foreground="Black" FontWeight="Bold">
<Grid x:Name="GvAdd">
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0.6">
<GradientStop Color="#FFDE7E13"/>
<GradientStop Color="#FF321966" Offset="1"/>
</LinearGradientBrush>
</Grid.Background>
<Label x:Name="LblUserCode0" Content="Codice Utente:" HorizontalAlignment="Left" Height="25" VerticalAlignment="Top" Width="100" FontWeight="Bold" Foreground="Black" Grid.ColumnSpan="2"/>
<TextBox x:Name="TxtUserCode0" HorizontalAlignment="Left" Height="20" Margin="4,25,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="175" FontWeight="Normal" MaxLength="25" MaxLines="1" Grid.ColumnSpan="2" Text="{Binding UserCode}"/>
<Label x:Name="LblLastName0" Content="Cognome:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="0,45,0,0" Foreground="Black" Grid.ColumnSpan="2"/>
<TextBox x:Name="TxtLastName0" HorizontalAlignment="Left" Height="20" Margin="4,68,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="677" FontWeight="Normal" MaxLength="100" MaxLines="1" Grid.ColumnSpan="2" Text="{Binding LastName}"/>
<Label x:Name="LblFirstName0" Content="Nome:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Center" Width="100" FontWeight="Bold" Foreground="Black" Grid.ColumnSpan="2"/>
<TextBox x:Name="TxtFirstName0" HorizontalAlignment="Left" Height="20" Margin="4,112,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="677" FontWeight="Normal" MaxLength="100" MaxLines="1" Grid.ColumnSpan="2" Text="{Binding FirstName}"/>
<Label x:Name="LblEmail0" Content="Mail:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="4,132,0,0" Foreground="Black" Grid.ColumnSpan="2"/>
<TextBox x:Name="TxtEmail0" HorizontalAlignment="Left" Height="20" Margin="4,161,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="345" FontWeight="Normal" MaxLength="50" MaxLines="1" Grid.ColumnSpan="2" Text="{Binding Email}"/>
<Label x:Name="LblAuthLevel0" Content="Livello di Aut. :" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="433,132,0,0" Foreground="Black" Grid.Column="1"/>
<TextBox x:Name="TxtAuthLevel0" HorizontalAlignment="Left" Height="18" Margin="483,161,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="18" FontWeight="Normal" MaxLength="1" MaxLines="1" Grid.Column="1" Text="{Binding AuthLevel}"/>
<Label x:Name="LblPassword0" Content="Password:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="756,0,0,0" Foreground="Black" Grid.Column="1"/>
<PasswordBox x:Name="TxtPassword0" HorizontalAlignment="Left" Height="20" Margin="756,25,0,0" VerticalAlignment="Top" Width="250" MaxLength="32" Grid.Column="1"/>
<CheckBox x:Name="CbIsActive0" Content="Attivo" HorizontalAlignment="Left" Height="20" Margin="660,161,0,0" VerticalAlignment="Top" Width="68" FontWeight="Bold" Foreground="Black" IsChecked="{Binding IsActive}"/>
<Button x:Name="BtnAdd0" Content="Aggiungi" HorizontalAlignment="Left" Height="25" Margin="1023,168,0,0" VerticalAlignment="Top" Width="100" Background="#FF0C6330" BorderBrush="Black" FontWeight="Bold" Foreground="Black" Click="BtnAdd0_Click"/>
</Grid>
</TabItem>
</TabControl>

C# 10 Code extract  
            if (mistake == 0)  
            {  
                //context.Password = this.TxtPassword1.Password;  
                context.SaveChanges();  
                // Deselect Item and Refresh all views .  
                DataGridList.SelectedItem = null;  
                CollectionViewSource.GetDefaultView(DataGridList.ItemsSource).Refresh();  
                this.TxtPassword1.Clear();  
            }  
            else  
            {  
                CollectionViewSource.GetDefaultView(DataGridList.ItemsSource).Refresh();  
            }  
  
        }  
        private void BtnAdd0_Click(object sender, RoutedEventArgs e)  
        {  
            NewUser.Password = this.TxtPassword0.Password;  
            context.Users.Add(NewUser);  
            context.SaveChanges();  
            DataGridList.SelectedItem = null;  
            CollectionViewSource.GetDefaultView(DataGridList.ItemsSource).Refresh();  
            NewUser = new User();  
            GvAdd.DataContext = NewUser;  
            this.TxtPassword0.Clear();  
        }  
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,785 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,029 questions
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,571 Reputation points Microsoft Vendor
    2022-06-17T02:52:31.06+00:00

    Add the NuGet Packages:

    • Microsoft.EntityFrameworkCore.Sqlite
    • Microsoft.Extensions.DependencyInjection

    App.xaml:

    <Application x:Class="PasswordEFCore.App"  
       ...  
                 Startup="OnStartup">  
        <Application.Resources>  
               
        </Application.Resources>  
    </Application>  
    

    App.xaml.cs:

    using Microsoft.EntityFrameworkCore;  
    using Microsoft.Extensions.DependencyInjection;  
      
    using System.Windows;  
      
    namespace PasswordEFCore  
    {  
      public partial class App : Application  
      {  
        private readonly ServiceProvider serviceProvider;  
        public App()  
        {  
          ServiceCollection services = new ServiceCollection();  
          services.AddDbContext<UserDbContext>(options =>  
          {  
            options.UseSqlite("Data Source = User.db");  
          });  
          services.AddSingleton<MainWindow>();  
          serviceProvider = services.BuildServiceProvider();  
        }  
        private void OnStartup(object s,StartupEventArgs e)  
        {  
          var mainWindow= serviceProvider.GetService<MainWindow>();  
          mainWindow.Show();  
        }  
      }  
    }  
    

    MainWindow.xaml:

    <Grid >  
            <StackPanel Grid.Row="3">  
                <DataGrid x:Name="DataGridList"  />  
                <TabControl x:Name="TblUserdetail" HorizontalAlignment="Left" Height="431"  Width="739">  
                    <TabItem Header="Modifica" FontWeight="Bold">  
                        <Grid>  
                            <Grid x:Name="GvUpdate" DataContext="{Binding ElementName=DataGridList, Path=SelectedItem}" Grid.ColumnSpan="2">  
                                <Grid.ColumnDefinitions>  
                                    <ColumnDefinition/>  
                                    <ColumnDefinition/>  
      
                                </Grid.ColumnDefinitions>  
                                <Label x:Name="LblUserCode1" Content="Codice Utente:" HorizontalAlignment="Left" Height="25" VerticalAlignment="Top" Width="100" FontWeight="Bold" Foreground="Black"/>  
                                <TextBox x:Name="TxtUserCode1" HorizontalAlignment="Left" Height="20" Margin="4,25,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="175" FontWeight="Normal" MaxLength="25" MaxLines="1" Text="{Binding Id}"/>  
                                <Label x:Name="LblLastName1" Content="Cognome:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="0,45,0,0" Foreground="Black"/>  
                                <TextBox x:Name="TxtLastName1" HorizontalAlignment="Left" Height="20" Margin="4,68,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="677" FontWeight="Normal" MaxLength="100" MaxLines="1" Text="{Binding Name}" Grid.ColumnSpan="2"/>  
      
                                <Label x:Name="LblPassword1" Content="Password:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Foreground="Black" Margin="56,0,0,0" Grid.Column="1"/>  
                                <PasswordBox x:Name="TxtPassword1" HorizontalAlignment="Left" Height="20" Margin="56,25,0,0" VerticalAlignment="Top"  
                                            local:PasswordHelper.Attach="True"   
                                           local:PasswordHelper.Password="{Binding ElementName=DataGridList , Path=SelectedItem.Password,  Mode=TwoWay}"   
                                               
                                             Width="250" MaxLength="32" Grid.Column="1" />  
      
                                <Button x:Name="BtnUpdate1" Content="Modifica" HorizontalAlignment="Left" Height="25"   
                                    Margin="223,168,0,0" VerticalAlignment="Top" Width="100" BorderBrush="Black" FontWeight="Bold" Foreground="Black" Click="BtnUpdate1_Click">  
                                    <Button.Background>  
                                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">  
                                            <GradientStop Color="#FFFFDD00"/>  
                                            <GradientStop Color="#FFFBB034" Offset="1"/>  
                                        </LinearGradientBrush>  
                                    </Button.Background>  
                                </Button>  
                            </Grid>  
                        </Grid>  
                    </TabItem>  
                    <TabItem Header="Aggiungi" Foreground="Black" FontWeight="Bold">  
                        <Grid x:Name="GvAdd"   >  
                            <Grid.ColumnDefinitions>  
                                <ColumnDefinition Width="22*"/>  
                                <ColumnDefinition Width="71*"/>  
                                <ColumnDefinition Width="274*"/>  
                                <ColumnDefinition Width="367*"/>  
                            </Grid.ColumnDefinitions>  
                            <Label x:Name="LblUserCode0" Content="Codice Utente:" HorizontalAlignment="Left" Height="25" VerticalAlignment="Top" Width="100" FontWeight="Bold" Foreground="Black" Grid.ColumnSpan="3"/>  
                            <TextBox x:Name="TxtUserCode0" HorizontalAlignment="Left" Height="20" Margin="4,25,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="175" FontWeight="Normal" MaxLength="25" MaxLines="1" Grid.ColumnSpan="3" Text="{Binding Id}"/>  
                            <Label x:Name="LblLastName0" Content="Cognome:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" FontWeight="Bold" Margin="0,45,0,0" Foreground="Black" Grid.ColumnSpan="3"/>  
                            <TextBox x:Name="TxtLastName0" HorizontalAlignment="Left" Height="20" Margin="4,68,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="677" FontWeight="Normal" MaxLength="100" MaxLines="1" Grid.ColumnSpan="4" Text="{Binding Name}"/>  
                            <Label x:Name="LblPassword0" Content="Password:" HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" Margin="55,0,0,0" Foreground="Black" Grid.Column="3"/>  
                            <PasswordBox x:Name="TxtPassword0" HorizontalAlignment="Left" Height="20" Margin="55,25,0,0"  
                                          local:PasswordHelper.Attach="True"   
                                           local:PasswordHelper.Password="{Binding Text}"  VerticalAlignment="Top" Width="250" MaxLength="32" Grid.Column="3"/>  
                            
                        </Grid>  
                    </TabItem>  
                </TabControl>  
            </StackPanel>  
        </Grid>  
    

    MainWindow.xaml.cs:

    using Microsoft.EntityFrameworkCore;  
    using System.ComponentModel;  
    using System.Linq;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Data;  
      
    namespace PasswordEFCore  
    {  
      public partial class MainWindow : Window  
      {  
        UserDbContext context;  
        public MainWindow(UserDbContext context)  
        {  
          this.context = context;  
          InitializeComponent();  
          GetUsers();  
        }  
        int mistake;  
        private void BtnUpdate1_Click(object sender, RoutedEventArgs e)  
        {  
          if (mistake == 0)  
          {  
            context.SaveChanges();  
            DataGridList.SelectedItem = null;  
            CollectionViewSource.GetDefaultView(DataGridList.ItemsSource).Refresh();  
            this.TxtPassword1.Clear();  
          }  
          else  
          {  
            CollectionViewSource.GetDefaultView(DataGridList.ItemsSource).Refresh();  
          }  
        }  
        private void GetUsers()  
        {  
          this.DataGridList.ItemsSource = context.Users.ToList();  
        }  
      
      }  
      public class User  
      {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public string Password { get;set;}  
      }  
      public class UserDbContext : DbContext, INotifyPropertyChanged  
      {  
        public UserDbContext(DbContextOptions<UserDbContext> options) : base(options)  
        {  
          Database.EnsureCreated();  
        }  
        public DbSet<User> Users { get; set; }  
      
        protected override void OnModelCreating(ModelBuilder modelBuilder)  
        {  
          modelBuilder.Entity<User>().HasData(GetUsers());  
          base.OnModelCreating(modelBuilder);  
        }  
        private User selectedUser;  
        public User SelectedUser { get { return selectedUser; } set { selectedUser = value; OnPropertyChanged(); } }  
        public event PropertyChangedEventHandler PropertyChanged;  
        internal void OnPropertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));  
      
        private User[] GetUsers()  
        {  
          return new User[]  
          {  
                 new User { Id = 1, Name = "TShirt",Password="124"},  
                 new User { Id = 2, Name = "Shirt", Password="124"},  
                 new User { Id = 3, Name = "Socks",Password="124"},  
                 new User { Id = 4, Name = "Tshirt", Password="124"},  
          };  
        }  
      
      }  
      public static class PasswordHelper  
      {  
        public static readonly DependencyProperty PasswordProperty =  
            DependencyProperty.RegisterAttached("Password",  
            typeof(string), typeof(PasswordHelper),  
            new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));  
      
        public static readonly DependencyProperty AttachProperty =  
            DependencyProperty.RegisterAttached("Attach",  
            typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));  
      
        private static readonly DependencyProperty IsUpdatingProperty =  
           DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),  
           typeof(PasswordHelper));  
      
      
        public static void SetAttach(DependencyObject dp, bool value)  
        {  
          dp.SetValue(AttachProperty, value);  
        }  
      
        public static bool GetAttach(DependencyObject dp)  
        {  
          return (bool)dp.GetValue(AttachProperty);  
        }  
      
        public static string GetPassword(DependencyObject dp)  
        {  
          return (string)dp.GetValue(PasswordProperty);  
        }  
      
        public static void SetPassword(DependencyObject dp, string value)  
        {  
          dp.SetValue(PasswordProperty, value);  
        }  
      
        private static bool GetIsUpdating(DependencyObject dp)  
        {  
          return (bool)dp.GetValue(IsUpdatingProperty);  
        }  
      
        private static void SetIsUpdating(DependencyObject dp, bool value)  
        {  
          dp.SetValue(IsUpdatingProperty, value);  
        }  
      
        private static void OnPasswordPropertyChanged(DependencyObject sender,  
            DependencyPropertyChangedEventArgs e)  
        {  
          PasswordBox passwordBox = sender as PasswordBox;  
          passwordBox.PasswordChanged -= PasswordChanged;  
      
          if (!(bool)GetIsUpdating(passwordBox))  
          {  
            passwordBox.Password = (string)e.NewValue;  
          }  
          passwordBox.PasswordChanged += PasswordChanged;  
        }  
      
        private static void Attach(DependencyObject sender,  
            DependencyPropertyChangedEventArgs e)  
        {  
          PasswordBox passwordBox = sender as PasswordBox;  
      
          if (passwordBox == null)  
            return;  
      
          if ((bool)e.OldValue)  
          {  
            passwordBox.PasswordChanged -= PasswordChanged;  
          }  
      
          if ((bool)e.NewValue)  
          {  
            passwordBox.PasswordChanged += PasswordChanged;  
          }  
        }  
      
        private static void PasswordChanged(object sender, RoutedEventArgs e)  
        {  
          PasswordBox passwordBox = sender as PasswordBox;  
          SetIsUpdating(passwordBox, true);  
          SetPassword(passwordBox, passwordBox.Password);  
          SetIsUpdating(passwordBox, false);  
        }  
      }  
    }  
    

    The result:

    212268-4.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.