Click here to Skip to main content
12,957,071 members (57,384 online)
Click here to Skip to main content
Add your own
alternative version

Stats

43.5K views
13 bookmarked
Posted 10 Jun 2009

Binding Passwords

, 29 Jun 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Binding Passwords

Those who've been following my blog and conversations with the WPF Disciples know that I love the databinding power of WPF, and in almost all cases I'm a very happy bunny. There is one stain in the awe inspiring goodness that is bound applications, and that’s the PasswordBox. Superficially, this control looks like a textbox, but there is a problem when you write MVVM applications and rely on binding the way I do; you can't bind to it. Yes, you heard it right, you can't bind with a PasswordBox.

There’s a good reason for this lack of binding – PasswordBox.Password is not a Dependency Property, ostensibly because this would result in the password being stored in clear text in memory, which is a potential security concern. If, however, you aren't too worried about this potential security breach, there is a workaround. Good news, folks – the following class (taken from my forthcoming Twitter client Songbird) is a way to perform binding with the PasswordBox.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace SongBird.Infrastructure
{
    /// <span class="code-SummaryComment"><summary>
</span>    /// This class adds binding capabilities to the standard WPF PasswordBox.
    /// <span class="code-SummaryComment"></summary>
</span>    public class BoundPasswordBox
    {
        #region BoundPassword
        private static bool _updating = false;

        /// <span class="code-SummaryComment"><summary>
</span>        /// BoundPassword Attached Dependency Property
        /// <span class="code-SummaryComment"></summary>
</span>        public static readonly DependencyProperty BoundPasswordProperty =
            DependencyProperty.RegisterAttached("BoundPassword",
                typeof(string),
                typeof(BoundPasswordBox),
                new FrameworkPropertyMetadata(string.Empty, OnBoundPasswordChanged));

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets the BoundPassword property.
        /// <span class="code-SummaryComment"></summary>
</span>        public static string GetBoundPassword(DependencyObject d)
        {
            return (string)d.GetValue(BoundPasswordProperty);
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Sets the BoundPassword property.
        /// <span class="code-SummaryComment"></summary>
</span>        public static void SetBoundPassword(DependencyObject d, string value)
        {
            d.SetValue(BoundPasswordProperty, value);
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Handles changes to the BoundPassword property.
        /// <span class="code-SummaryComment"></summary>
</span>        private static void OnBoundPasswordChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox password = d as PasswordBox;
            if (password != null)
            {
                // Disconnect the handler while we're updating.
                password.PasswordChanged -= PasswordChanged;
            }

            if (e.NewValue != null)
            {
                if (!_updating)
                {
                    password.Password = e.NewValue.ToString();
                }
            }
            else
            {
                password.Password = string.Empty;
            }
            // Now, reconnect the handler.
            password.PasswordChanged += new RoutedEventHandler(PasswordChanged);
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Handles the password change event.
        /// <span class="code-SummaryComment"></summary>
</span>        static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox password = sender as PasswordBox;
            _updating = true;
            SetBoundPassword(password, password.Password);
            _updating = false;
        }

        #endregion
    }
}

Using it couldn't be simpler, just add a reference to the namespace in your XAML, and update your PasswordBox with the BoundPasswordBox class. You've now got a bindable PasswordBox.

<PasswordBox

    Grid.Column="1"

    Grid.Row="2"

    Margin="5,5,5,5"

    password:BoundPasswordBox.BoundPassword="{Binding Path=Password,
        Mode=TwoWay,
        UpdateSourceTrigger=PropertyChanged}"

    VerticalAlignment="Center"/>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pete O'Hanlon
CEO
United Kingdom United Kingdom
A developer for over 30 years, I've been lucky enough to write articles and applications for Code Project as well as the Intel Ultimate Coder - Going Perceptual challenge. I live in the North East of England with 2 wonderful daughters and a wonderful wife.

I am not the Stig, but I do wish I had Lotus Tuned Suspension.

You may also be interested in...

Comments and Discussions

 
QuestionPasswordBox.Password Pin
jperlinski21-Jan-13 4:31
memberjperlinski21-Jan-13 4:31 
QuestionThanks! Pin
cruzanPC3-May-12 3:45
membercruzanPC3-May-12 3:45 
GeneralMy vote of 5 Pin
Robert Croll21-Feb-11 15:52
memberRobert Croll21-Feb-11 15:52 
GeneralBoundPasswordProperty default value Pin
sbhl1-Sep-10 22:37
membersbhl1-Sep-10 22:37 
GeneralRe: BoundPasswordProperty default value Pin
Pete O'Hanlon1-Sep-10 22:46
mvpPete O'Hanlon1-Sep-10 22:46 
GeneralRe: BoundPasswordProperty default value Pin
sbhl1-Sep-10 23:10
membersbhl1-Sep-10 23:10 
GeneralRe: BoundPasswordProperty default value Pin
sbhl2-Sep-10 0:01
membersbhl2-Sep-10 0:01 
GeneralRe: BoundPasswordProperty default value Pin
sbhl2-Sep-10 2:39
membersbhl2-Sep-10 2:39 
GeneralGreat! Pin
Paul Eie12-Apr-10 0:06
memberPaul Eie12-Apr-10 0:06 
GeneralRe: Great! Pin
Pete O'Hanlon12-Apr-10 1:40
mvpPete O'Hanlon12-Apr-10 1:40 
QuestionIs there any reason the binding password code not work? Pin
JJChen4019-Jun-09 15:22
memberJJChen4019-Jun-09 15:22 
AnswerRe: Is there any reason the binding password code not work? Pin
Pete O'Hanlon21-Jun-09 11:02
mvpPete O'Hanlon21-Jun-09 11:02 
GeneralRe: Is there any reason the binding password code not work? [modified] Pin
JJChen403-Jul-09 7:29
memberJJChen403-Jul-09 7:29 
Generalthanks. Pin
Michael Sync10-Jun-09 15:54
memberMichael Sync10-Jun-09 15:54 
GeneralRe: thanks. Pin
Pete O'Hanlon10-Jun-09 21:54
mvpPete O'Hanlon10-Jun-09 21:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170525.1 | Last Updated 29 Jun 2009
Article Copyright 2009 by Pete O'Hanlon
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid