Make the WPF PasswordBox Bindable

In WPF, the PasswordBox control is used to securely enter passwords. Unlike the standard TextBox, the PasswordBox does not expose a bindable Password property by default. This is intentional because passwords are sensitive data, and WPF avoids exposing them through the standard dependency property binding mechanism.

However, when developing an application using the MVVM (Model-View-ViewModel) pattern, we often need to bind the password entered by the user to a property in the ViewModel.

In this article, we will learn how to create a bindable PasswordBox in WPF using an attached dependency property, allowing us to bind the password to our ViewModel and use it in our application.

Password Box

Getting Started

WPF provides several controls for handling user input, such as TextBox, ComboBox, and PasswordBox. While the TextBox supports data binding out of the box through its Text property, the PasswordBox does not support binding its Password property directly.

For example, the following binding works perfectly with a TextBox:
</> XAML  
<TextBox Text="{Binding UserName, Mode=TwoWay}" />


However, attempting to bind a PasswordBox directly like this is not supported:
</> XAML  
<PasswordBox Password="{Binding UserName, Mode=TwoWay}" />


This is because the Password property of the WPF PasswordBox is not a dependency property.

To overcome this limitation, we can create a custom helper class that exposes an attached dependency property and synchronizes the password between the PasswordBox control and the ViewModel.

Prerequisites
Before proceeding, you should have:
  • Basic knowledge of C# and WPF.
  • Understanding of the MVVM architectural pattern.
  • Visual Studio installed.
  • A WPF project ready for development.

Create a Bindable PasswordBox in WPF Using MVVM

Create a PasswordBoxHelper Class

First, create a class named PasswordBoxHelper in your WPF project. This class will contain an attached dependency property called Password, which we will use to bind the password entered in the PasswordBox to a ViewModel property.

The attached property will be responsible for synchronizing password changes in both directions:
  • When the user enters a password, it updates the ViewModel.
  • When the ViewModel updates the password, it updates the PasswordBox.

Create a class named PasswordBoxHelper.cs and add the following code.
</> C#
using System.Windows;
using System.Windows.Controls;
namespace WpfApp.Helpers
{
  public static class PasswordBoxHelper
  {
    public static readonly DependencyProperty PasswordProperty =
    DependencyProperty.RegisterAttached(
    "Password",
    typeof(string),
    typeof(PasswordBoxHelper),
    new FrameworkPropertyMetadata(
    string.Empty,
    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
    OnPasswordChanged));
    public static string GetPassword(DependencyObject obj)
    {
      return (string)obj.GetValue(PasswordProperty);
    }
    public static void SetPassword(DependencyObject obj, string value)
    {
      obj.SetValue(PasswordProperty, value);
    }
    private static void OnPasswordChanged(
    DependencyObject d,
    DependencyPropertyChangedEventArgs e)
    {
      if (d is PasswordBox passwordBox)
      {
        // Subscribe to the PasswordChanged event only once
        passwordBox.PasswordChanged -= PasswordBox_PasswordChanged;
        passwordBox.PasswordChanged += PasswordBox_PasswordChanged;
        // Update PasswordBox when the ViewModel changes the password
        string newPassword = e.NewValue as string ?? string.Empty;
        if (passwordBox.Password != newPassword)
        {
          passwordBox.Password = newPassword;
        }
      }
    }
    private static void PasswordBox_PasswordChanged(
    object sender,
    RoutedEventArgs e)
    {
      if (sender is PasswordBox passwordBox)
      {
        // Update the attached property when the user enters a password
        SetPassword(passwordBox, passwordBox.Password);
      }
    }
  }
}

Let's understand the important parts of the PasswordBoxHelper class.

Here, we register an attached dependency property named Password using below code. The BindsTwoWayByDefault option allows the property to support two-way data binding by default.

</> C#
public static readonly DependencyProperty PasswordProperty =
    DependencyProperty.RegisterAttached(
        "Password",
        typeof(string),
        typeof(PasswordBoxHelper),
        new FrameworkPropertyMetadata(
            string.Empty,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            OnPasswordChanged));

The OnPasswordChanged method is registered as the property change callback. Whenever the attached property changes, this method is invoked.

If you're unfamiliar with Attached Properties in WPF, you can refer to my previous article, Attached Property in WPF: Complete Guide with Examples, where I explained the concept in detail with practical examples.

</> C#
public static readonly DependencyProperty PasswordProperty =
    DependencyProperty.RegisterAttached(
        "Password",
        typeof(string),
        typeof(PasswordBoxHelper),
        new FrameworkPropertyMetadata(
            string.Empty,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            OnPasswordChanged));

Then two methods GetPassword and SetPassword are used with attached properties to provide a convenient way to access the registered dependency property value. They act as wrapper methods around GetValue() and SetValue().

</> C#
public static string GetPassword(DependencyObject obj)
{
    return (string)obj.GetValue(PasswordProperty);
}

public static void SetPassword(DependencyObject obj, string value)
{
    obj.SetValue(PasswordProperty, value);
}

Here, RegisterAttached() registers a dependency property named Password that can be attached to other controls, such as a PasswordBox.

However, registering the property alone does not provide the convenient static methods GetPassword() and SetPassword() that you use to access it.

These methods are wrappers around the DependencyObject methods GetValue() and SetValue(). When WPF processes this binding, it uses the getter and setter methods to access the attached property.

This allows WPF's binding engine to interact with your custom attached property.

OnPasswordChanged method is called whenever the attached Password property changes.

It performs two operations:
  • Subscribes to the PasswordChanged event of the PasswordBox.
  • Updates the actual PasswordBox whenever the attached property value changes.

The comparison between the current password and the new password prevents unnecessary assignments.

Whenever the user enters or modifies the password, the PasswordChanged event is raised.

We read the current password from the PasswordBox and update the attached dependency property using SetPassword(). Since the property is bindable, the new password is automatically propagated to the ViewModel.

Using PasswordBoxHelper Class in PasswordBox

Now that we have created the PasswordBoxHelper, we can use it in our XAML. First, add the namespace of the helper class to your XAML window.

</> XAML
xmlns:helpers="clr-namespace:WpfApp.Helpers"

Next, add the PasswordBox control and bind the attached property to the Password property of your MVVM ViewModel.

</> XAML
<PasswordBox
Height="35"
Width="250"
helpers:PasswordBoxHelper.Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Here, we use helpers:PasswordBoxHelper.Password instead of the standard Password property.

The UpdateSourceTrigger=PropertyChanged ensures that the ViewModel is updated immediately whenever the user types or changes the password.

Summary

Although this approach makes the PasswordBox bindable and convenient to use with MVVM, it is important to understand that the password is stored as a regular string in the ViewModel.

Strings are immutable in .NET, and the password may remain in memory until it is no longer referenced and the garbage collector eventually reclaims that memory.

Therefore:
  • Use this approach only when password binding is required by your application.
  • Avoid logging or debugging the password.
  • Do not store passwords in plain text in configuration files or databases.
  • Clear the password from the ViewModel after authentication when it is no longer required.
  • Prefer secure authentication mechanisms and avoid keeping passwords in memory longer than necessary.

The PasswordBox itself provides some protection by not exposing its password as a regular bindable dependency property, but adding a binding helper means the password is now accessible through your ViewModel.

Summary

By default, the WPF PasswordBox does not support direct binding to a ViewModel. However, we can overcome this limitation by creating an attached dependency property and synchronizing it with the PasswordBox.PasswordChanged event.

Using this approach, we can integrate the PasswordBox into an MVVM architecture without creating additional code-behind logic in our view.

This technique is useful when building login screens, authentication forms, and other WPF applications where the password needs to be accessible from the ViewModel.

Thanks

Kailash Chandra Behera

I am an IT professional with over 12 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

نموذج الاتصال