WPF 中使用附加属性解决 PasswordBox 的数据绑定问题
1、前言
在 WPF 开发中 View 中的数据展示我们常通过 Binding 进行绑定。但是,使用 Binding 有一个前提:绑定的目标只能是依赖属性。 而 PasswordBox 控件中的 Password 并不是一个依赖属性,所以我们在使用 Password 时无法直接进行数据绑定。为了解决这个问题,我们就需要自己定义依赖属性。标题中的 “附加属性” 是依赖属性的一种特殊形式。
2、实现步骤
注:附加属性的定义方式:在 Visual Studio 中输入 propa ,然后按下两次 Tab 键即可。
2.1、定义一个 LoginPasswordBoxHelper 类,并在页面 xaml 代码中添加命名空间,该类用于辅助解决数据绑定问题。
xmlns:vm="clr-namespace:PasswordBoxDemo.ViewModel"
2.2、在类中添加用于绑定的 Password 属性
public static class LoginPasswordBoxHelper
{
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(LoginPasswordBoxHelper), new PropertyMetadata(""));
}
这个时候就可以在页面的 xaml 中的 PasswordBox 中添加如下数据绑定了:
<PasswordBox Width="200" Height="30"
vm:LoginPasswordBoxHelper.Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
但是,这时候只是提供了一个属性给 PasswordBox 用于 Binding,输入内容后数据没有任何更改效果。
因为当在 PasswordBox 中填写密码时,没有启动对应的事件将密码 Changed 到后端 ViewModel 中的 Password 属性
这时就需要再建一个附加属性 IsPasswordBindingEnable,用于给 PasswordBox 的更改添加事件,并在事件中更改到 后端 ViewModel 中的 Password 属性。
2.3、添加附加属性 IsPasswordBindingEnable,用于给 PasswordBox 的添加更改事件
当 IsPasswordBindingEnable="True" 时,给 PasswordBox 的 PasswordChanged 事件添加处理程序PasswordBoxPasswordChanged;
PasswordBoxPasswordChanged 作用:当页面中 PasswordBox 输入的值发生改变时,通过 SetPassword 完成数据更改,从而实现完整的数据绑定功能。
<PasswordBox Width="200" Height="30"
vm:LoginPasswordBoxHelper.IsPasswordBindingEnable="True"
vm:LoginPasswordBoxHelper.Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
public static bool GetIsPasswordBindingEnable(DependencyObject obj)
{
return (bool)obj.GetValue(IsPasswordBindingEnableProperty);
}
public static void SetIsPasswordBindingEnable(DependencyObject obj, bool value)
{
obj.SetValue(IsPasswordBindingEnableProperty, value);
}
public static readonly DependencyProperty IsPasswordBindingEnableProperty =
DependencyProperty.RegisterAttached("IsPasswordBindingEnable", typeof(bool), typeof(LoginPasswordBoxHelper),
new FrameworkPropertyMetadata(OnIsPasswordBindingEnabledChanged));
private static void OnIsPasswordBindingEnabledChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var passwordBox = obj as PasswordBox;
if (passwordBox != null)
{
passwordBox.PasswordChanged -= PasswordBoxPasswordChanged;
if ((bool)e.NewValue)
{
passwordBox.PasswordChanged += PasswordBoxPasswordChanged;
}
}
}
static void PasswordBoxPasswordChanged(object sender, RoutedEventArgs e)
{
var passwordBox = (PasswordBox)sender;
if (!String.Equals(GetPassword(passwordBox), passwordBox.Password))
{
SetPassword(passwordBox, passwordBox.Password);
}
}
3、完整代码
3.1、页面代码
Login.xaml
<Window
x:Class="PasswordBoxDemo.Login"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:PasswordBoxDemo.ViewModel"
Title="MainWindow"
Width="450"
Height="400"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox x:Name="tbUserName"
Text="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Width="200" Height="30" />
<PasswordBox Grid.Row="1" Width="200" Height="30"
vm:LoginPasswordBoxHelper.IsPasswordBindingEnable="True"
vm:LoginPasswordBoxHelper.Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button x:Name="btnLogin" Grid.Row="2"
Content="登录"
Width="150"
Height="30" />
</Grid>
</Window>
Login.xaml.cs
using PasswordBoxDemo.ViewModel;
using System.Windows;
namespace PasswordBoxDemo
{
public partial class Login : Window
{
private MainViewModel resource;
public Login()
{
InitializeComponent();
resource = new MainViewModel();
this.DataContext = resource;
}
}
}
3.2、数据绑定辅助类 LoginPasswordBoxHelper
using System;
using System.Windows;
using System.Windows.Controls;
namespace PasswordBoxDemo.ViewModel
{
public static class LoginPasswordBoxHelper
{
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(LoginPasswordBoxHelper), new PropertyMetadata(""));
public static bool GetIsPasswordBindingEnable(DependencyObject obj)
{
return (bool)obj.GetValue(IsPasswordBindingEnableProperty);
}
public static void SetIsPasswordBindingEnable(DependencyObject obj, bool value)
{
obj.SetValue(IsPasswordBindingEnableProperty, value);
}
public static readonly DependencyProperty IsPasswordBindingEnableProperty =
DependencyProperty.RegisterAttached("IsPasswordBindingEnable", typeof(bool), typeof(LoginPasswordBoxHelper),
new FrameworkPropertyMetadata(OnIsPasswordBindingEnabledChanged));
private static void OnIsPasswordBindingEnabledChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var passwordBox = obj as PasswordBox;
if (passwordBox != null)
{
passwordBox.PasswordChanged -= PasswordBoxPasswordChanged;
if ((bool)e.NewValue)
{
passwordBox.PasswordChanged += PasswordBoxPasswordChanged;
}
}
}
static void PasswordBoxPasswordChanged(object sender, RoutedEventArgs e)
{
var passwordBox = (PasswordBox)sender;
if (!String.Equals(GetPassword(passwordBox), passwordBox.Password))
{
SetPassword(passwordBox, passwordBox.Password);
}
}
}
}
3.3、其它代码
ViewModel:
using GalaSoft.MvvmLight;
namespace PasswordBoxDemo.ViewModel
{
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
}
private string userName;
public string UserName
{
get { return userName; }
set { userName = value; RaisePropertyChanged(); }
}
private string password;
public string Password
{
get { return password; }
set { password = value; RaisePropertyChanged(); }
}
}
}
4、附加功能:输入框添加水印
实现水印添加也可以用类似上述的方法实现,具体步骤如下:
4.1、在 LoginPasswordBoxHelper 类中添加附加属性 ShowWaterMark,用与切换水印展示状态;
public static bool GetShowWaterMark(DependencyObject obj)
{
return (bool)obj.GetValue(ShowWaterMarkProperty);
}
public static void SetShowWaterMark(DependencyObject obj, bool value)
{
obj.SetValue(ShowWaterMarkProperty, value);
}
/// <summary>
/// 控制水印显示
/// </summary>
public static readonly DependencyProperty ShowWaterMarkProperty =
DependencyProperty.RegisterAttached("ShowWaterMark", typeof(bool), typeof(LoginPasswordBoxHelper),
new FrameworkPropertyMetadata(true, OnShowWaterMarkChanged));
private static void OnShowWaterMarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
4.2、自定义水印展示样式
<Window.Resources>
<Style x:Key="textbox" TargetType="{x:Type TextBox}">
<Setter Property="Padding" Value="2,5,0,0"/>
<Setter Property="FontSize" Value="14"/>
<Style.Triggers>
<Trigger Property="Text" Value="">
<Setter Property="Background">
<Setter.Value>
<VisualBrush AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<TextBlock Padding="5,3,0,0" Background="Transparent" Foreground="Silver" FontSize="14" Text="请输入用户名"></TextBlock>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="password" TargetType="{x:Type PasswordBox}">
<Setter Property="Padding" Value="2,5,0,0"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type PasswordBox}">
<Border Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}" SnapsToDevicePixels="true">
<Grid>
<ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
<StackPanel Orientation="Horizontal" Visibility="Visible" Name="myWaterMark">
<TextBlock Padding="3" Background="Transparent" Foreground="Silver" FontSize="14"
Text="请输入密码"/>
</StackPanel>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Visibility" TargetName="myWaterMark" Value="Collapsed"/>
</Trigger>
<Trigger Property="vm:LoginPasswordBoxHelper.ShowWaterMark" Value="False">
<Setter Property="Visibility" TargetName="myWaterMark" Value="Collapsed"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
5、效果展示

WPF 中使用附加属性解决 PasswordBox 的数据绑定问题的更多相关文章
- MVVM模式和在WPF中的实现(二)数据绑定
MVVM模式解析和在WPF中的实现(二) 数据绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- 由一次PasswordBox密码绑定引发的疑问 ---> WPF中的附加属性的定义,以及使用。
1,前几天学习一个项目的时候,遇到了PasswordBox这个控件,由于这个控件的Password属性,不是依赖属性,所以不能和ViewModel层进行数据绑定. 2,但是要实现前后端彻底的分离,就需 ...
- WPF 中使用附加属性,将任意 UI 元素或控件裁剪成圆形(椭圆)
不知从什么时候开始,头像流行使用圆形了,于是各个平台开始追逐显示圆形裁剪图像的技术.WPF 作为一个优秀的 UI 框架,当然有其内建的机制支持这种圆形裁剪. 不过,内建的机制仅支持画刷,而如果被裁剪的 ...
- MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息
MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二 ...
- MVVM设计模式和WPF中的实现(四)事件绑定
MVVM设计模式和在WPF中的实现(四) 事件绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- MVVM模式解析和在WPF中的实现(三)命令绑定
MVVM模式解析和在WPF中的实现(三) 命令绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- MVVM模式和在WPF中的实现(一)MVVM模式简介
MVVM模式解析和在WPF中的实现(一) MVVM模式简介 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在 ...
- MVVM设计模式和在WPF中的实现(四) 事件绑定
系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中的实现(三)命令绑定 MVVM模式解析和在WPF中的 ...
- MVVM模式解析和在WPF中的实现(五)View和ViewModel的通信
MVVM模式解析和在WPF中的实现(五) View和ViewModel的通信 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 M ...
- WPF中使用第三方字体选择器
原文:WPF中使用第三方字体选择器 起因 到WPF的字体可以设置的东西变得非常的多,而却没有提供专用的字体选择对话框,甚至于WinFrom的FontDialog也是不能直接用来设置WPF中的字体.解决 ...
随机推荐
- 基于QUBO模型的多体分子对接
技术背景 本文分享内容来自于最新的一篇名为Multibody molecular docking on a quantum annealer的文章,这篇文章的核心思想,是使用QUBO(二次受限二元优化 ...
- c# countDownEvent类
前言 把异步先总结完吧. countDownEvent 这东西是干什么的呢? 比如说我们比赛跑步,我们需要得出的是第一二三名得出后就可以先统计出来,因为比较重要,后面没有获得获奖名次的可以后续统计出来 ...
- Scratch3自定义积木块之新增积木块
在Scratch3.0的二次开发中,新功能的研发和扩展离不开积木块的添加,这篇主要讲解Scratch3.0中新增积木块部分 Scratch3.0中对于新增积木块有两种方式: 1. 初始化积木块方式 ...
- 推荐一波微软家的浏览器:EDGE
前段时间英雄联盟(LOL)队伍 EDG 夺冠成为热门事件,上了各大热搜,即使大家不玩英雄联盟,相信也多多少少有听说相关信息吧! 今天我们的主角并不是 EDG,而是微软的新版浏览器 EDGE !!! 微 ...
- 谷歌浏览器新功能 Copy Declaration
不知道最近大家有没有发现,从谷歌浏览器开发者工具复制 Css 代码到 Vs Code,粘贴之后 Css 代码错乱了.昨天在复制样式代码的时候,突然发现复制的 Css 代码粘贴之后就错乱了.具体表现如下 ...
- 【笔记】Oracle Offset 以及力扣
[笔记]Oracle Offset offset 代表跳过前 n 行,如果表少于 n+1 条记录,结果集将是空的:比如 n = 100,表示从 101 开始往后查. fetch next 代表往后查 ...
- 力扣1620(java&python)-网络信号最好的坐标(中等)
题目: 给你一个数组 towers 和一个整数 radius . 数组 towers 中包含一些网络信号塔,其中 towers[i] = [xi, yi, qi] 表示第 i 个网络信号塔的坐标是 ...
- 使用 Gradio 的“热重载”模式快速开发 AI 应用
在这篇文章中,我将展示如何利用 Gradio 的热重载模式快速构建一个功能齐全的 AI 应用.但在进入正题之前,让我们先了解一下什么是重载模式以及 Gradio 为什么要采用自定义的自动重载逻辑.如果 ...
- HarmonyOS NEXT 实战开发—Grid和List内拖拽交换子组件位置
介绍 本示例分别通过onItemDrop()和onDrop()回调,实现子组件在Grid和List中的子组件位置交换. 效果图预览 使用说明: 拖拽Grid中子组件,到目标Grid子组件位置,进行两者 ...
- CCO x Hologres:实时数仓高可用架构再次升级,双11大规模落地
简介:本文将会介绍今年是如何在去年基础上进行实时数仓高可用架构升级,并成功大规模落地双11. 作者 | 梅酱 来源 | 阿里技术公众号 一 2021年双11总结 2021年阿里巴巴双11期间,由CC ...