前言
将一个与占位符绑定的TextBlock放入VisualBrush内,在TextBox的Text为空时使用VisualBrush绘制背景,不为空时背景设为Null。
正因为如此,如果文本框设置了背景,使用此方法就会覆盖原有的背景。但一般不会设置TextBox的背景。
TextBox实现Placeholder
方式1 使用附加属性
添加引用
1 | xmlns:local="clr-namespace:ZView" |
使用方式
1 | <TextBox |
添加类PlaceholderManager
1 | using System.Collections.Generic; |
方式2 使用自定义组件
使用方式
1 | <local:PlaceholderTextBox |
自定义组件
1 | using System.Windows; |
PasswordBox双向绑定
WPF 的 PasswordBox
控件因为安全原因,默认不支持MVVM的双向数据绑定,那么我们在MVVM开发的过程中如何解决这个问题呢?
添加附加属性
1 | using System.Windows; |
在需要用的PasswordBox
中添加上面写的附加属性Password
即可:
1 | <PasswordBox Helper:PasswordBoxHelper.Attach="True" |
PasswordBox实现Placeholder
PasswordBox实现Placeholder不能跟TextBox使用同样方法实现的原因有两个
- PasswordBox的Password属性不支持绑定,这个可以自己添加属性解决。
- 设置背景的TextBlock中的文字会变成加密状态。
第二点就导致了TextBox实现Placeholder的方式在这里行不通。
添加属性
1 | /* |
模板
1 | <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> |
使用
1 | <PasswordBox |
其中主要是添加以下两行
1 | local:PasswordBoxHelper.Placeholder="请输入密码" |
PasswordBox实现Placeholder(失败)
当输入框中没有密码的时候显示如下,并没有显示请输入密码
这是按照TextBox实现Placeholder的方式来实现的,最终不行。
1 | using System; |
调用方式
1 | <PasswordBox |