WPF中使用附加属性解决MVVM模式中PasswordBox无法绑定的问题

学习网站文章更全:C#学习网站 点击跳转

如果文章信息错误或过时,请移步至我的博客:https://www.lincol29.cn
内容更新仅在个人博客可见(请到我的博客获取第一手信息),欢迎关注!

PasswordBox的属性绑定

1.新建PasswordBoxHelper 使用propa创建Pwd以及IsBindPwd两个附加属性。

  1. Pwd附加属性中,默认值为string.Empty 当值发生改变时触发回调函数OnPwdChanged
    • 在OnPwdChanged函数中将改变的值传给PasswordBox的Password
    • IsBindPwd附加属性中,new PropertyMetadata(false, OnPropertyChanged),默认值为false 当为true时,触发OnPropertyChanged
    • OnPropertyChanged当为新值,给PasswordBox的PasswordChanged事件绑定方法Pbox_PasswordChanged
    • Pbox_PasswordChanged方法主要是调用SetPwd方法,设置Pwd附加属性

详细代码如下

public class PasswordBoxHelper
{
    public static string GetPwd(DependencyObject obj)
    {
        return (string)obj.GetValue(PwdProperty);
    }

    public static void SetPwd(DependencyObject obj, string value)
    {
        obj.SetValue(PwdProperty, value);
    }

    //new PropertyMetadata(string.Empty, OnPwdChanged)
    //默认值为string.Empty 当值发生改变时触发回调函数OnPwdChanged
    // Using a DependencyProperty as the backing store for Pwd.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PwdProperty =
        DependencyProperty.RegisterAttached("Pwd", typeof(string), typeof(PasswordBoxHelper), new PropertyMetadata(string.Empty, OnPwdChanged));

    private static void OnPwdChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        PasswordBox pbox = d as PasswordBox;

        if (pbox == null)
            return;
        pbox.Password = (string)e.NewValue;

        SetSelection(pbox, pbox.Password.Length, 0);
    }

    /// <summary>
    /// 设置光标位置
    /// </summary>
    /// <param name="passwordBox"></param>
    /// <param name="start">光标开始位置</param>
    /// <param name="length">选中长度</param>
    private static void SetSelection(PasswordBox passwordBox, int start, int length)
    {
        passwordBox.GetType()
                   .GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic)
                   .Invoke(passwordBox, new object[] { start, length
     });
    }

    public static bool GetIsBindPwd(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsBindPwdProperty);
    }

    public static void SetIsBindPwd(DependencyObject obj, bool value)
    {
        obj.SetValue(IsBindPwdProperty, value);
    }

    // Using a DependencyProperty as the backing store for IsBindPwd.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty IsBindPwdProperty =
        DependencyProperty.RegisterAttached("IsBindPwd", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        PasswordBox pbox = d as PasswordBox;
        if (pbox == null)
            return;
        if ((bool)e.NewValue)
            pbox.PasswordChanged += Pbox_PasswordChanged;
        if ((bool)e.OldValue)
            pbox.PasswordChanged -= Pbox_PasswordChanged;
    }

    private static void Pbox_PasswordChanged(object sender, RoutedEventArgs e)
    {
        PasswordBox pwd = (PasswordBox)sender;

        //设置附加属性的值
        SetPwd(pwd, pwd.Password);
    }

2.新建一个MyPasswordVm 依赖属性,用来绑定PasswordBox

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }


    public string MyPasswordVM
    {
        get { return (string)GetValue(MyPasswordVMProperty); }
        set { SetValue(MyPasswordVMProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyPasswordVM.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyPasswordVMProperty =
        DependencyProperty.Register("MyPasswordVM", typeof(string), typeof(MainWindow));



    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPasswordVM = "258";
        //MessageBox.Show(MyPasswordVM);
    }

3.前端界面展示

  1. PasswordBox绑定一下两下附加属性
  2. local:PasswordBoxHelper.IsBindPwd=“True”
  3. local:PasswordBoxHelper.Pwd=“{Binding MyPasswordVM,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}”

img

<StackPanel>
    <PasswordBox x:Name="pbox"  FontSize="20" 
                 local:PasswordBoxHelper.IsBindPwd="True"
                 local:PasswordBoxHelper.Pwd="{Binding MyPasswordVM,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
    <TextBox Text="{Binding MyPasswordVM}"    FontSize="20"  />
    <!--绑定附加属性Pwd,验证MyPasswordVM和pwd之间是否互相关联-->
    <TextBox Text="{Binding ElementName=pbox,Path=(local:PasswordBoxHelper.Pwd)}"  FontSize="20"/>
    <Button Content="同步" Click="Button_Click" FontSize="20"/>
</StackPanel>
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值