WPF PasswordBox进行数据绑定方法

作者:louzi 时间:2022-05-23 03:53:11 

目录
  • 问题描述

  • 解决办法

本文介绍下PasswordBox进行数据绑定的方法,本文参考链接。

本文完整示例程序见GitHub。

问题描述

PasswordBox的Password属性不是依赖属性,因此无法进行数据绑定。

解决办法

该问题的解决办法有多种,本文介绍如何通过添加附加属性解决该问题。

附加属性是说一个属性本不属于某个对象,但由于某种需求附加到该对象上,通过附加属性可以实现将属性与宿主解耦的目的。附加属性本质上就是依赖属性,只是它们在属性包装器和注册时有区别。注册附加属性使用RegisterAttached方法,注册依赖属性使用Register方法,这两个方法的参数差别并不大。

首先添加一个PasswordBoxBindingHelper类,该类包含一个附加属性(snippet:propa+两次tab),通过设置该属性的PropertyChangedCallback将改变通知到PasswordBox.Password,并通过添加对PasswordBox.PasswordChanged事件的响应来响应PasswordBox.Password的改变。有了该附加属性,即可进行数据绑定。


public static string GetPasswordContent(DependencyObject obj) => (string)obj.GetValue(PasswordContentProperty);

public static void SetPasswordContent(DependencyObject obj, string value) => obj.SetValue(PasswordContentProperty, value);

public static readonly DependencyProperty PasswordContentProperty =
   DependencyProperty.RegisterAttached("PasswordContent", typeof(string), typeof(PasswordBoxBindingHelper),
   new PropertyMetadata(string.Empty, OnPasswordContentPropertyChanged));

private static void OnPasswordContentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
   var box = d as PasswordBox;
   box.PasswordChanged -= OnPasswordChanged;
   var password = (string)e.NewValue;
   if (box != null && box.Password != password)
       box.Password = password;
   box.PasswordChanged += OnPasswordChanged;
}

private static void OnPasswordChanged(object sender, RoutedEventArgs e)
{
   var box = sender as PasswordBox;
   SetPasswordContent(box, box.Password);
}

然后在View中使用该附加属性进行数据绑定,本文示例中主窗口包含一个PasswordBox控件及一个Button按钮:


// xaml 绑定附加属性
<Window ...
       xmlns:local="clr-namespace:PasswordBoxBinding"
       Title="PasswordBoxBinding" Height="300" Width="450" WindowStartupLocation="CenterScreen">

<Grid>
       <StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
           <PasswordBox MinWidth="200" Height="30" BorderBrush="LightGray" BorderThickness="2"
                        local:PasswordBoxBindingHelper.PasswordContent="{Binding Password,Mode=TwoWay}"/>
           <Rectangle Width="20"/>
           <Button Width="80" Height="30" Content="查看密码" Command="{Binding ClickedCommand}"/>
       </StackPanel>
   </Grid>
</Window>

//xaml.cs 设置绑定源
public MainWindow()
{
   InitializeComponent();
   this.DataContext = new MainWindowViewModel();
}

最后创建ViewModel进行逻辑处理:


// ViewModel
public class MainWindowViewModel : INotifyPropertyChanged
{
   public string Password
   {
       get => _password;
       set
       {
           _password = value;
           OnPropertyChanged();
       }
   }

public DelegateCommand ClickedCommand => _clickedCommand ?? (_clickedCommand = new DelegateCommand { ExecuteAction = OnClicked });

// 使用CallerMemberName特性简化代码,并可以避免手动输入错误
   public void OnPropertyChanged([CallerMemberName] string name = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

private void OnClicked(object o) => MessageBox.Show($"password: {Password}");

public event PropertyChangedEventHandler PropertyChanged;

private DelegateCommand _clickedCommand;
   private string _password;
}

// 实现ICommand
public class DelegateCommand : ICommand
{
   public bool CanExecute(object parameter) => CanExecuteAction?.Invoke(parameter) ?? true;

public void Execute(object parameter) => ExecuteAction?.Invoke(parameter);

public event EventHandler CanExecuteChanged;

public Action<object> ExecuteAction { get; set; }
   public Func<object, bool> CanExecuteAction { get; set; }
}

来源:https://www.cnblogs.com/louzixl/archive/2021/06/22/14919985.html

标签:WPF,PasswordBox,数据绑定
0
投稿

猜你喜欢

  • Android带进度的圆形进度条

    2023-08-05 21:47:18
  • C#获取ListView鼠标下的Item实例

    2023-04-29 11:45:10
  • C# winfrom 模拟ftp文件管理实现代码

    2023-07-15 16:29:48
  • C#实现拼手气红包算法

    2023-07-27 13:52:18
  • C#装箱与拆箱操作的深入讲解

    2023-04-29 19:10:06
  • Android自定义控件之组合控件学习笔记分享

    2022-09-18 01:09:22
  • Spring整合junit的配置过程图解

    2022-12-18 16:37:48
  • Android App开发中使用RecyclerView替代ListView的实践

    2021-06-14 06:53:36
  • Flutter Shell自动化打包解放双手

    2021-09-17 18:39:15
  • Spring注解配置IOC,DI的方法详解

    2023-10-18 14:06:23
  • C# 计算DataTime的4种时间差的方法(相差天数、相差小时、相差分钟、相差秒)

    2022-12-08 10:37:07
  • 基于ClasspathResource路径问题的解决

    2022-03-29 21:23:22
  • Java递归实现迷宫游戏

    2023-08-26 07:33:16
  • Java设计模式之观察者模式(Observer模式)介绍

    2022-10-16 04:40:42
  • 解决IDEA导入javaWeb项目注解爆红的问题

    2021-08-07 13:42:02
  • Redis集群与SSM整合使用方法

    2023-07-02 02:17:05
  • 微服务间调用Retrofit在Spring Cloud Alibaba中的使用

    2022-09-29 23:13:42
  • Spring AOP实现权限检查的功能

    2023-08-10 06:51:14
  • Android 实现可任意拖动的悬浮窗功能(类似悬浮球)

    2023-08-07 10:19:05
  • Android使用shape绘制阴影图层阴影效果示例

    2021-11-25 01:19:39
  • asp之家 软件编程 m.aspxhome.com