简介

效果图如下:

使用的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的更多相关文章

  1. 在Java中编写带占位符的SQL语句

    C#中SQL中带占位符的语句 假设有一张学员信息表Student,通过表中的ID来找学员,查询的SQL语句如下 string sql = string.Format("select * fr ...

  2. SpringMVC(七) RequestMapping 路径中带占位符的URL

    使用方法:在@RequestMapping("/delete/{id}")中,通过{id}带入pathvariable,然后在方法中,通过@PathVariable("变 ...

  3. Swift3 重写一个带占位符的textView

    class PlaceStrTextView: UIView,UITextViewDelegate{ var palceStr = "即将输入的信息" //站位文字 var inp ...

  4. 用mysql写带占位符的select语句

    sql.append(" AND t.f_user_name LIKE CONCAT('%',?,'%')");//模糊查询 sql.append(" AND t.f_u ...

  5. 【SpringMVC】SpringMVC系列3之@PathVariable映射URL占位符参数

    3.@PathVariable映射URL占位符参数 3.1.概述 带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义. ...

  6. spring源码解析(一)---占位符解析替换

    一.结构类图 ①.PropertyResolver : Environment的顶层接口,主要提供属性检索和解析带占位符的文本.bean.xml配置中的所有占位符例如${}都由它解析 ②.Config ...

  7. SpringMVC(三):@RequestMapping中的URL中设定通配符,可以使用@PathVariable映射URL绑定的占位符

    1)带占位符的URL是Spring3.0新增的功能,该功能在SpringMVC向REST目标挺进发展过程中具有里程碑的意义. 2)通过@PathVariable可以将URL中占位符参数绑定到控制器处理 ...

  8. 004 @PathVariable映射URL绑定的占位符

    一: 1.介绍 带占位符的URL是spring 3.0新增的功能,是向REST发展的重要阶段. @PathVariable可以将URL中占位符参数绑定到控制器处理的方法的入参中:URL中的{xxx}占 ...

  9. SpringBoot环境属性占位符解析和类型转换

    前提 前面写过一篇关于Environment属性加载的源码分析和扩展,里面提到属性的占位符解析和类型转换是相对复杂的,这篇文章就是要分析和解读这两个复杂的问题.关于这两个问题,选用一个比较复杂的参数处 ...

随机推荐

  1. JAVA常见面试题之Forward和Redirect的区别 (转发和重定向)

    阅读目录 一:间接请求转发(Redirect) 二:直接请求转发(Forward) 用户向服务器发送了一次HTTP请求,该请求可能会经过多个信息资源处理以后才返回给用户,各个信息资源使用请求转发机制相 ...

  2. asp代码审计

    今天给大家带来的是asp程序的代码审计,asp和aspx代码审计来说,有很多相同的地方. 正好今天要交任务,最近的目标站的子域名使用了这个cms,但是版本不一定是这个,好累. 本文作者:i春秋签约作家 ...

  3. canvas绘制五角星详细过程

    canvas绘制 <canvas id="straight"></canvas> <script> var canvas = document. ...

  4. “ping”简单报错理解

    了解ABC类IP地址:网络.主机.子网.广播. ———————————————————————————- 学会ping: ping www.itxdm.me 网络检测:ping某一主机可以正常启动!( ...

  5. [转]NSProxy实现AOP方便为ios应用实现异常处理策略

    [转载自:http://blog.csdn.net/yanghua_kobe/article/details/8395535] 前段时间关注过objc实现的AOP,在GitHub找到了其中的两个库:A ...

  6. 第一站:CLion安装教程与环境配置

    原文来自:http://www.sunmey.cn/thread-129-1-1.html 本人:找了很久才找到的CLion安装教程与环境配置,这里分享给大家~ 这里要说明的一点是CLion是要钱的, ...

  7. Java多线程——volatile关键字、发布和逸出

    1.volatile关键字 Java语言提供了一种稍弱的同步机制,即volatile变量.被volatile关键字修饰的变量不会被缓存在寄存器或者对其他处理器不可见的地方,因此在每次读取volatit ...

  8. 关于ajax学习

    一.Ajax是XMLHttpRequest对象,javascript,XML,CSS,DOM等多种技术的组合 1.XML :(可扩展的标记语言) 提供了用于描述结构化数据的格式,适用于不同应用间的数据 ...

  9. IntelliJ IDEA 18 周岁,吐血推进珍藏已久的必装插件

    IntelliJ IDEA是目前最好最强最智能的Java IDE,前几天,他刚刚年满18岁.  本文,给大家推荐几款我私藏已久的,自己经常使用的,可以提升代码效率的插件. IDEA插件简介 常见的I ...

  10. spark持久化

    spark持久化:cache .persist.checkpoint 一.cache持久化 cache实际上是persist的一种简化方式,是一种懒执行的,执行action类算子才会触发,cahce后 ...