PasswordBox
Password实现绑定
xmlns:utl="clr-namespace:Project1.Utility"
utl:PasswordBoxHelper.Password="{Binding ConfirmPassword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
using System.Windows;
using System.Windows.Controls;
public class PasswordBoxHelper
{
// 防止附加属性值与控件属性值循环触发复制
private static bool _bUpdating = false;
public static string GetPassword(DependencyObject obj)
{
return (string)obj.GetValue(PasswordProperty);
}
public static void SetPassword(DependencyObject obj, string value)
{
obj.SetValue(PasswordProperty, value);
}
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxHelper), new PropertyMetadata(null, OnPasswordPropertyChanged));
public static bool GetAttach(DependencyObject obj)
{
return (bool)obj.GetValue(AttachProperty);
}
public static void SetAttach(DependencyObject obj, bool value)
{
obj.SetValue(AttachProperty, value);
}
public static readonly DependencyProperty AttachProperty =
DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false, OnAttachPropertyChanged));
/// <summary>
/// 附加属性值变化后推给 控件
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is PasswordBox pbox)
{
pbox.PasswordChanged -= Password_PasswwordChanged;
if (_bUpdating)
{
pbox.Password = e.NewValue?.ToString();
int start = (pbox.Password ?? string.Empty).Length;
SetCursor(pbox, start);
}
pbox.PasswordChanged += Password_PasswwordChanged;
}
}
/// <summary>
/// 控件的值变化后推送给 附加属性
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnAttachPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is PasswordBox pbox)
{
pbox.PasswordChanged -= Password_PasswwordChanged;
pbox.PasswordChanged += Password_PasswwordChanged;
_bUpdating = (bool)e.NewValue;
}
}
private static void Password_PasswwordChanged(object sender, RoutedEventArgs e)
{
if (sender is PasswordBox pbox)
{
_bUpdating = true;
SetPassword(pbox, pbox.Password);
_bUpdating = false;
}
}
}
设置光标位置
/// <summary>
/// 设置光标位置
/// </summary>
/// <param name="pbox"></param>
/// <param name="index"></param>
private static void SetCursor(PasswordBox pbox, int index)
{
if (index < 0)
{
return;
}
if (index > pbox.Password.Length)
{
index = pbox.Password.Length;
}
pbox.GetType().GetMethod("Select", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.Invoke(pbox, new object[] { index, 0 });
}