using System; using System.Linq; using System.Windows.Controls; using System.Windows; namespace CyberX8_Themes.CustomControls { public class CustomPasswordBox : TextBox { #region Variables #region Data #endregion public String Password { get { return (String)GetValue(PwdTextProperty); } set { SetValue(PwdTextProperty, value); } } /// /// The DependencyProperty for the ItemsSource property. /// Flags: None /// Default Value: null /// public static readonly DependencyProperty PwdTextProperty = DependencyProperty.Register("PwdText", typeof(string), typeof(PasswordBox), new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnPwdTextChanged))); private static void OnPwdTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { PasswordBox ic = (PasswordBox)d; string oldValue = e.OldValue as string; string newValue = e.NewValue as string; } public String PasswordChar { get { return (String)GetValue(PwdCharProperty); } set { SetValue(PwdTextProperty, value); } } /// /// The DependencyProperty for the ItemsSource property. /// Flags: None /// Default Value: null /// public static readonly DependencyProperty PwdCharProperty = DependencyProperty.Register("PasswordChar", typeof(String), typeof(PasswordBox), new FrameworkPropertyMetadata("*", new PropertyChangedCallback(OnPwdCharChanged))); private static void OnPwdCharChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } private string SetPwdString(string value) { try { var str = value + ""; var list = str.ToArray(); var dst = ""; var pwd = "*"; if (PasswordChar != null) { pwd = PasswordChar + ""; } foreach (var item in list) { dst += pwd; } return dst; } catch { } return null; } #endregion #region static Variables #endregion #region Methods #region 构造函数 protected override void OnTextInput(System.Windows.Input.TextCompositionEventArgs e) { base.OnTextInput(e); } bool ChangeToPwd = false; protected override void OnTextChanged(TextChangedEventArgs e) { var str = SetPwdString(Text); if (ChangeToPwd) { return; } ChangeToPwd = true; int offset = 0; foreach (var item in e.Changes) { offset = item.Offset; if (item.RemovedLength > 0) { Password = Password.Remove(item.Offset, item.RemovedLength); } if (item.AddedLength > 0) { var insertStr = Text.Substring(item.Offset, item.AddedLength); Password = Password.Insert(item.Offset, insertStr); offset = item.Offset + item.AddedLength; } } Text = str; this.Select(offset, 0); base.OnTextChanged(e); ChangeToPwd = false; } #endregion #endregion #region static Methods #endregion #region Event #endregion } }