WPF带占位符的TextBox
简介
效果图如下:

使用的XAML代码如下:
<Window x:Class="PlaceHolderTextBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PlaceHolderTextBox"
Title="MainWindow"
Width="525"
Height="350">
<StackPanel>
<local:PlaceholderTextBox Placeholder="查询" />
<TextBox x:Name="TxtTest" local:PlaceholderManager.Placeholder="搜索" />
</StackPanel>
</Window>
其中第一个是带占位符的文本框,第二个使用附加属性装饰在现有的文本框上。
原理
将一个与占位符绑定的TextBlock放入VisualBrush内,在TextBox的Text为空时使用VisualBrush绘制背景,不为空时背景设为Null。
正因为如此,如果文本框设置了背景,使用此方法就会覆盖原有的背景。但一般不会设置TextBox的背景。
带占位符的文本框
代码较简单,如下:
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media; namespace PlaceHolderTextBox
{
/// <summary>
/// 带点位符的文本输入控件
/// </summary>
public class PlaceholderTextBox:TextBox
{
#region Fields /// <summary>
/// 占位符的文本框
/// </summary>
private readonly TextBlock _placeholderTextBlock = new TextBlock(); /// <summary>
/// 占位符的画刷
/// </summary>
private readonly VisualBrush _placeholderVisualBrush = new VisualBrush(); #endregion Fields #region Properties /// <summary>
/// 占位符的依赖属性
/// </summary>
public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.Register(
"Placeholder", typeof (string), typeof (PlaceholderTextBox),
new FrameworkPropertyMetadata("请在此输入", FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary>
/// 占位符
/// </summary>
public string Placeholder
{
get { return (string) GetValue(PlaceholderProperty); }
set { SetValue(PlaceholderProperty, value); }
} #endregion Properties #region Public Methods public PlaceholderTextBox()
{
var binding = new Binding
{
Source = this,
Path = new PropertyPath("Placeholder")
};
_placeholderTextBlock.SetBinding(TextBlock.TextProperty, binding);
_placeholderTextBlock.FontStyle = FontStyles.Italic; _placeholderVisualBrush.AlignmentX = AlignmentX.Left;
_placeholderVisualBrush.Stretch = Stretch.None;
_placeholderVisualBrush.Visual = _placeholderTextBlock; Background = _placeholderVisualBrush;
TextChanged += PlaceholderTextBox_TextChanged;
} #endregion Public Methods #region Events Handling /// <summary>
/// 文本变化的响应
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PlaceholderTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
Background = string.IsNullOrEmpty(Text) ? _placeholderVisualBrush : null;
} #endregion Events Handling }
}
使用附加属性
代码较简单,如下:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media; namespace PlaceHolderTextBox
{
/// <summary>
/// 占位符的管理类
/// </summary>
public class PlaceholderManager
{
#region Fields /// <summary>
/// 文本框和Visual画刷对应的字典
/// </summary>
private static readonly Dictionary<TextBox, VisualBrush> TxtBrushes = new Dictionary<TextBox, VisualBrush>(); #endregion Fields #region Attached DependencyProperty /// <summary>
/// 占位符的附加依赖属性
/// </summary>
public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.RegisterAttached(
"Placeholder", typeof(string), typeof(PlaceholderManager),
new PropertyMetadata("请在此处输入", OnPlaceholderChanged)); /// <summary>
/// 获取占位符
/// </summary>
/// <param name="obj">占位符所在的对象</param>
/// <returns>占位符</returns>
public static string GetPlaceholder(DependencyObject obj)
{
return (string)obj.GetValue(PlaceholderProperty);
} /// <summary>
/// 设置占位符
/// </summary>
/// <param name="obj">占位符所在的对象</param>
/// <param name="value">占位符</param>
public static void SetPlaceholder(DependencyObject obj, string value)
{
obj.SetValue(PlaceholderProperty, value);
} #endregion Attached DependencyProperty #region Events Handling /// <summary>
/// 占位符改变的响应
/// </summary>
/// <param name="d">来源</param>
/// <param name="e">改变信息</param>
public static void OnPlaceholderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var txt = d as TextBox;
if ((txt != null) && (!TxtBrushes.ContainsKey(txt)))
{
var placeholderTextBlock = new TextBlock();
var binding = new Binding
{
Source = txt,
//绑定到附加属性
Path = new PropertyPath("(0)", PlaceholderProperty)
};
placeholderTextBlock.SetBinding(TextBlock.TextProperty, binding);
placeholderTextBlock.FontStyle = FontStyles.Italic; var placeholderVisualBrush = new VisualBrush
{
AlignmentX = AlignmentX.Left,
Stretch = Stretch.None,
Visual = placeholderTextBlock
}; txt.Background = placeholderVisualBrush; txt.TextChanged += PlaceholderTextBox_TextChanged;
txt.Unloaded += PlaceholderTextBox_Unloaded; TxtBrushes.Add(txt, placeholderVisualBrush);
}
} /// <summary>
/// 文本变化的响应
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void PlaceholderTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var txt = sender as TextBox;
if ((txt != null) && (TxtBrushes.ContainsKey(txt)))
{
var placeholderVisualBrush = TxtBrushes[txt];
txt.Background = string.IsNullOrEmpty(txt.Text) ? placeholderVisualBrush : null;
}
} /// <summary>
/// 文本框卸载的响应
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void PlaceholderTextBox_Unloaded(object sender, RoutedEventArgs e)
{
var txt = sender as TextBox;
if ((txt != null) && (TxtBrushes.ContainsKey(txt)))
{
TxtBrushes.Remove(txt); txt.TextChanged -= PlaceholderTextBox_TextChanged;
txt.Unloaded -= PlaceholderTextBox_Unloaded;
}
} #endregion Events Handling }
}
WPF带占位符的TextBox的更多相关文章
- 在Java中编写带占位符的SQL语句
C#中SQL中带占位符的语句 假设有一张学员信息表Student,通过表中的ID来找学员,查询的SQL语句如下 string sql = string.Format("select * fr ...
- SpringMVC(七) RequestMapping 路径中带占位符的URL
使用方法:在@RequestMapping("/delete/{id}")中,通过{id}带入pathvariable,然后在方法中,通过@PathVariable("变 ...
- Swift3 重写一个带占位符的textView
class PlaceStrTextView: UIView,UITextViewDelegate{ var palceStr = "即将输入的信息" //站位文字 var inp ...
- 用mysql写带占位符的select语句
sql.append(" AND t.f_user_name LIKE CONCAT('%',?,'%')");//模糊查询 sql.append(" AND t.f_u ...
- 【SpringMVC】SpringMVC系列3之@PathVariable映射URL占位符参数
3.@PathVariable映射URL占位符参数 3.1.概述 带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义. ...
- spring源码解析(一)---占位符解析替换
一.结构类图 ①.PropertyResolver : Environment的顶层接口,主要提供属性检索和解析带占位符的文本.bean.xml配置中的所有占位符例如${}都由它解析 ②.Config ...
- SpringMVC(三):@RequestMapping中的URL中设定通配符,可以使用@PathVariable映射URL绑定的占位符
1)带占位符的URL是Spring3.0新增的功能,该功能在SpringMVC向REST目标挺进发展过程中具有里程碑的意义. 2)通过@PathVariable可以将URL中占位符参数绑定到控制器处理 ...
- 004 @PathVariable映射URL绑定的占位符
一: 1.介绍 带占位符的URL是spring 3.0新增的功能,是向REST发展的重要阶段. @PathVariable可以将URL中占位符参数绑定到控制器处理的方法的入参中:URL中的{xxx}占 ...
- SpringBoot环境属性占位符解析和类型转换
前提 前面写过一篇关于Environment属性加载的源码分析和扩展,里面提到属性的占位符解析和类型转换是相对复杂的,这篇文章就是要分析和解读这两个复杂的问题.关于这两个问题,选用一个比较复杂的参数处 ...
随机推荐
- WebService-php- 1(16)
最近看了挺多关于php中webservice的资料,感谢燕十八的分享,帮助了我构建服务端的过程.将学习笔记记录如下,其中包含燕十八的笔记. WebService 1 快速了解WebService 通俗 ...
- LOJ#6044. 「雅礼集训 2017 Day8」共(Prufer序列)
题面 传送门 题解 答案就是\(S(n-k,k)\times {n-1\choose k-1}\) 其中\(S(n,m)\)表示左边\(n\)个点,右边\(m\)个点的完全二分图的生成树个数,它的值为 ...
- fd - 更好的 find 命令
欢迎关注我的公众号 spider-learn fd(https://github.com/sharkdp/fd) 是 find 命令的一个更现代的替换. 对比一下 查找名字含有某个字符的文件 OLD ...
- 【性能分析】使用Intel VTune Amplifier
本文转自 https://software.intel.com/zh-cn/blogs/2010/11/10/amplxe-cl/版权归原作者所有,如原作者有任何不允许转载之理由,本文将自行删除. I ...
- Java 读写锁的实现
一. synchronized和ReentrantLock的对比 到现在,看到多线程中,锁定的方式有2种:synchronized和ReentrantLock.两种锁定方式各有优劣,下面简单对比 ...
- Centos7.4下安装Mysql8.0.15
一.下载Mysql Mysql下载地址:https://dev.mysql.com/downloads/mysql/ 二.卸载Linux自带的mariadb 安装Mysql之前需要卸载maria ...
- 【转载】Java 9 新特性——模块化
来自 <http://www.jianshu.com/p/053a5ca89bbb#> 前言 年,我们将迎来 Java 语言的 22 岁生日,22岁,对于一个人而言,正是开始大展鸿图的年纪 ...
- 配置bootstrap环境
bootstrap是一个优雅,灵活,可扩展的前端工具集,可搭建WEB页面的HTML,CSS,JavaScript工具集,最重要的是它的栅格系统. 这里不做更多的详细介绍具体可参照官方网站:http:/ ...
- Python数据结构之序列及其操作
数据结构是计算机存储,组织数据的方式.数据结构是指相互之间存在一种或多种特定关系的数据元素的集合. 在Python中,最基本的数据结构为序列(sequence).序列中的每个元素都有编号:从0开始递增 ...
- (转)Mysql数据库主从心得整理
Mysql数据库主从心得整理 原文:http://blog.sae.sina.com.cn/archives/4666 管理mysql主从有2年多了,管理过200多组mysql主从,几乎涉及到各个版本 ...