C# WPF PasswordBox MVVM 绑定数据 焦点离开输入框更新

在C# WPF中实现PasswordBox的MVVM绑定,‌并确保在焦点离开时才更新数据,‌确实需要一些特殊的处理,‌因为PasswordBox控件本身并不直接支持双向数据绑定。‌本文采用创建 PasswordHelper 附加属性类来实现

public static class PasswordHelper
{
    public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached(
                "Password",
                typeof(string),
                typeof(PasswordHelper),
                new PropertyMetadata(string.Empty, OnPasswordPropertyChanged)
            );
    public static string GetPassword(DependencyObject PasswordObject)
    {
        return (string)PasswordObject.GetValue(PasswordProperty);
    }

    public static void SetPassword(DependencyObject PasswordObject, string PasswordValue)
    {
        PasswordObject.SetValue(PasswordProperty, PasswordValue);
    }

    private static void OnPasswordPropertyChanged(DependencyObject PasswordObject, DependencyPropertyChangedEventArgs Password)
    {
        PasswordBox PasswordBox = (PasswordBox)PasswordObject;
        PasswordBox.LostFocus -= PasswordChanged;
        PasswordBox.Password = Password.NewValue.ToString();
        PasswordBox.LostFocus += PasswordChanged;
    }
    private static void PasswordChanged(object PasswordObject, RoutedEventArgs _)
    {
        SetPassword((PasswordBox)PasswordObject, ((PasswordBox)PasswordObject).Password);
    }
}

引入命名空间 xmlns:Common=“clr-namespace:命名空间名”

<PasswordBox 
	Common:PasswordHelper.Password="{Binding V.ButtonName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值