WPF中使用附加属性解决MVVM模式中PasswordBox无法绑定的问题
本文最后更新于155 天前,其中的信息可能已经过时,如有错误请发送邮件到2289035571@QQ.COM

PasswordBox的属性绑定

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

  1. Pwd附加属性中,默认值为string.Empty 当值发生改变时触发回调函数OnPwdChanged
  2. 在OnPwdChanged函数中将改变的值传给PasswordBox的Password
  3. IsBindPwd附加属性中,new PropertyMetadata(false, OnPropertyChanged),默认值为false 当为true时,触发OnPropertyChanged
  4. OnPropertyChanged当为新值,给PasswordBox的PasswordChanged事件绑定方法Pbox_PasswordChanged
  5. 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>
觉得有帮助可以投喂下博主哦~感谢!
作者:Lincol
本文链接:https://www.lincol29.cn/wpf%e4%b8%ad%e4%bd%bf%e7%94%a8%e9%99%84%e5%8a%a0%e5%b1%9e%e6%80%a7%e8%a7%a3%e5%86%b3mvvm%e6%a8%a1%e5%bc%8f%e4%b8%adpasswordbox%e6%97%a0%e6%b3%95%e7%bb%91%e5%ae%9a%e7%9a%84%e9%97%ae%e9%a2%98
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0协议转载请注明文章地址及作者哦~
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇