和之前一样,先来看看效果:

  

  这个TextBox可设置水印,可设置必填和正则表达式验证。

  验证?没错,就是验证! 就是在输入完成后,控件一旦失去焦点就会自动验证!会根据我开放出来的“是否可以为空”属性进行验证,一旦为空,则控件变为警告样式。

  但这还不是最特别的,为了各种手机号啊,邮箱啊的验证,我还开放了一个正则表达式的属性,在这个属性中填上正则表达式,同上, 一旦失去焦点就会自动验证输入的内容能否匹配正则表达式,如果不能匹配,则控件变为警告样式。

  之后,代码还可以通过我开放的另一个属性来判断当前输入框的输入是否有误!

  好了,来看代码吧:

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrl="clr-namespace:KAN.WPF.XCtrl.Controls">
<Style TargetType="{x:Type ctrl:XTextBox}">
<!--StyleFocusVisual在上一篇里说了-->
<Style.Resources>
<ResourceDictionary Source="/KAN.WPF.Xctrl;component/Themes/CommonStyle.xaml"/>
</Style.Resources>
<Setter Property="FocusVisualStyle" Value="{StaticResource StyleFocusVisual}"/>
<Setter Property="BorderBrush" Value="Silver"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ctrl:XTextBox}">
<Border Name="brdText" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}" SnapsToDevicePixels="true" Padding="2">
<Grid>
<ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
<StackPanel Orientation="Horizontal" Visibility="Collapsed" Name="stpWatermark">
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center"
FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}"
Foreground="{Binding XWmkForeground, RelativeSource={RelativeSource TemplatedParent}}"
Text="{Binding XWmkText, RelativeSource={RelativeSource TemplatedParent}}" Cursor="IBeam" />
</StackPanel>
<ContentPresenter></ContentPresenter>
</Grid>
</Border>
<ControlTemplate.Triggers>
<!--当失去焦点并且没有输入任何内容时-->
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Text" Value=""/>
<Condition Property="IsFocused" Value="False"/>
</MultiTrigger.Conditions>
<MultiTrigger.Setters>
<Setter Property="Visibility" TargetName="stpWatermark" Value="Visible"/>
</MultiTrigger.Setters>
</MultiTrigger>
<!--当验证失败时-->
<Trigger Property="XIsError" Value="true">
<Setter TargetName="brdText" Property="BorderBrush" Value="Red" />
<Setter TargetName="brdText" Property="Background" Value="Beige" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

  再来看看CS:

 using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Input;
using System.Text.RegularExpressions; namespace KAN.WPF.XCtrl.Controls
{
/// <summary>
/// 扩展输入框:可设置水印,可设置必填,可设置正则表达式验证
/// </summary>
public class XTextBox:TextBox
{
#region 依赖属性
public static readonly DependencyProperty XWmkTextProperty;//水印文字
public static readonly DependencyProperty XWmkForegroundProperty;//水印着色
public static readonly DependencyProperty XIsErrorProperty;//是否字段有误
public static readonly DependencyProperty XAllowNullProperty;//是否允许为空
public static readonly DependencyProperty XRegExpProperty;//正则表达式
#endregion #region 内部方法
/// <summary>
/// 注册事件
/// </summary>
public XTextBox()
{
this.LostFocus += new RoutedEventHandler(XTextBox_LostFocus);
this.GotFocus += new RoutedEventHandler(XTextBox_GotFocus);
this.PreviewMouseDown += new MouseButtonEventHandler(XTextBox_PreviewMouseDown);
} /// <summary>
/// 静态构造函数
/// </summary>
static XTextBox()
{
//注册依赖属性
XTextBox.XWmkTextProperty = DependencyProperty.Register("XWmkText", typeof(String), typeof(XTextBox), new PropertyMetadata(null));
XTextBox.XAllowNullProperty = DependencyProperty.Register("XAllowNull", typeof(bool), typeof(XTextBox), new PropertyMetadata(true));
XTextBox.XIsErrorProperty = DependencyProperty.Register("XIsError", typeof(bool), typeof(XTextBox), new PropertyMetadata(false));
XTextBox.XRegExpProperty = DependencyProperty.Register("XRegExp", typeof(string), typeof(XTextBox), new PropertyMetadata(""));
XTextBox.XWmkForegroundProperty = DependencyProperty.Register("XWmkForeground", typeof(Brush),
typeof(XTextBox), new PropertyMetadata(Brushes.Silver));
FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(XTextBox), new FrameworkPropertyMetadata(typeof(XTextBox)));
} /// <summary>
/// 失去焦点时检查输入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void XTextBox_LostFocus(object sender, RoutedEventArgs e)
{
this.XIsError = false;
if (XAllowNull == false && this.Text.Trim() == "")
{
this.XIsError = true;
}
if (Regex.IsMatch(this.Text.Trim(), XRegExp) == false)
{
this.XIsError = true;
}
} /// <summary>
/// 获得焦点时选中文字
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void XTextBox_GotFocus(object sender, RoutedEventArgs e)
{
this.SelectAll();
} /// <summary>
/// 鼠标点击时选中文字
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void XTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (this.IsFocused == false)
{
TextBox textBox = e.Source as TextBox;
textBox.Focus();
e.Handled = true;
}
}
#endregion #region 公布属性
/// <summary>
/// 公布属性XWmkText(水印文字)
/// </summary>
public String XWmkText
{
get
{
return base.GetValue(XTextBox.XWmkTextProperty) as String;
}
set
{
base.SetValue(XTextBox.XWmkTextProperty, value);
}
} /// <summary>
/// 公布属性XWmkForeground(水印着色)
/// </summary>
public Brush XWmkForeground
{
get
{
return base.GetValue(XTextBox.XWmkForegroundProperty) as Brush;
}
set
{
base.SetValue(XTextBox.XWmkForegroundProperty, value);
}
} /// <summary>
/// 公布属性XIsError(是否字段有误)
/// </summary>
public bool XIsError
{
get
{
return (bool)base.GetValue(XTextBox.XIsErrorProperty);
}
set
{
base.SetValue(XTextBox.XIsErrorProperty, value);
}
} /// <summary>
/// 公布属性XAllowNull(是否允许为空)
/// </summary>
public bool XAllowNull
{
get
{
return (bool)base.GetValue(XTextBox.XAllowNullProperty);
}
set
{
base.SetValue(XTextBox.XAllowNullProperty, value);
}
} /// <summary>
/// 公布属性XRegExp(正则表达式)
/// </summary>
public string XRegExp
{
get
{
return base.GetValue(XTextBox.XRegExpProperty) as string;
}
set
{
base.SetValue(XTextBox.XRegExpProperty, value);
}
}
#endregion
}
}

  怎么样?还算不错吧!我觉得这个控件的用处算是最大的了!用上这个和上一篇的Button基本可以完成很多WPF项目了!

  不过~好像还少了个主窗体!没错!下一篇就来说说怎么自定义主窗体!

  有疑问的多留言哟!

WPF自定义控件(二)——TextBox的更多相关文章

  1. WPF自定义控件二:Border控件与TextBlock控件轮播动画

    需求:实现Border轮播动画与TextBlock动画 XAML代码如下: <Window.Resources> <Storyboard x:Key="OnLoaded1& ...

  2. WPF自定义控件与样式(3)-TextBox & RichTextBox & PasswordBox样式、水印、Label标签、功能扩展

    一.前言.预览 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要是对文本 ...

  3. 【转】WPF自定义控件与样式(3)-TextBox & RichTextBox & PasswordBox样式、水印、Label标签、功能扩展

    一.前言.预览 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等. 本文主要是对文本输入控件进行样式开发,及相关扩展功能开发,主要内容包括: 基本文 ...

  4. WPF自定义控件(二)の重写原生控件样式模板

    话外篇: 要写一个圆形控件,用Clip,重写模板,去除样式引用圆形图片可以有这三种方式. 开发过程中,我们有时候用WPF原生的控件就能实现自己的需求,但是样式.风格并不能满足我们的需求,那么我们该怎么 ...

  5. 工作记录--WPF自定义控件,实现一个可设置编辑模式的TextBox

    原文:工作记录--WPF自定义控件,实现一个可设置编辑模式的TextBox 1. 背景 因为最近在使用wpf开发桌面端应用,在查看页面需要把TextBox和Combox等控件设置为只读的.原本是个很简 ...

  6. WPF自定义控件与样式(1)-矢量字体图标(iconfont)

    一.图标字体 图标字体在网页开发上运用非常广泛,具体可以网络搜索了解,网页上的运用有很多例子,如Bootstrap.但在C/S程序中使用还不多,字体图标其实就是把矢量图形打包到字体文件里,就像使用一般 ...

  7. WPF自定义控件与样式(2)-自定义按钮FButton

    一.前言.效果图 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 还是先看看效果 ...

  8. WPF自定义控件与样式(15)-终结篇 & 系列文章索引 & 源码共享

    系列文章目录  WPF自定义控件与样式(1)-矢量字体图标(iconfont) WPF自定义控件与样式(2)-自定义按钮FButton WPF自定义控件与样式(3)-TextBox & Ric ...

  9. WPF自定义控件与样式(4)-CheckBox/RadioButton自定义样式

    一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: Che ...

  10. WPF自定义控件与样式(5)-Calendar/DatePicker日期控件自定义样式及扩展

    一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: 日历控 ...

随机推荐

  1. [经典算法] 蒙地卡罗法求 PI

    题目说明: 蒙地卡罗为摩洛哥王国之首都,该国位于法国与义大利国境,以赌博闻名.蒙地卡罗的基本原理为以乱数配合面积公式来进行解题,这种以机率来解题的方式带有赌博的意味,虽然在精确度上有所疑虑,但其解题的 ...

  2. linux_jvm_jmap_dump内存分析

    jmap命令   jmap命令 jmap命令可以获得运行中的jvm的堆的快照,从而可以离线分析堆,以检查内存泄漏,检查一些严重影响性能的大对象的创建,检查系统中什么对象最多,各种对象所占内存的大小等等 ...

  3. ionic Modal

    在ionic中,modal也是添加控制器写服务的~ 在modal.html页面中增加控制器:ng-controller="aboutCtrl"记住要给这个添加控制器.头部使其关闭按 ...

  4. codeforces 680C C. Bear and Prime 100(数论)

    题目链接: C. Bear and Prime 100 time limit per test 1 second memory limit per test 256 megabytes input s ...

  5. 有一种风格,叫做 Low Poly 3D

    原作:Simon阿文    杂交编辑者:RhinoC       个人更推崇使用第二款神器 ImageTriangulator :http://www.conceptfarm.ca/2013/port ...

  6. 数组去重算法,quickSort

    function removeRepeat(arr) { var arr2 = [] ,obj = {}; for (var i = 0; i<arr.length; i++) { var nu ...

  7. 如何防止Android应用代码被窃

    上一篇我们讲了apk防止反编译技术中的加壳技术,如果有不明白的可以查看我的上一篇博客http://my.oschina.net/u/2323218/blog/393372.接下来我们将介绍另一种防止a ...

  8. php数组编码转换函数的示例

    场景说明/问题描述: Ajax提交页面编码为gb2312,数据库编码为utf8,在不更改页面及数据库编码的情况下插入数据. 自定义函数:  代码如下 复制代码 function array_iconv ...

  9. JAVA 模糊查询方法

    当我们需要开发一个方法用来查询数据库的时候,往往会遇到这样一个问题:就是不知道用户到底会输入什么条件,那么怎么样处理sql语句才能让我们开发的方法不管接受到什么样的条件都可以正常工作呢?这时where ...

  10. Cocos2d-JS键盘事件

    Cocos2d-JS中的键盘事件与触摸事件不同,它没有空间方面信息.键盘事件不仅可以响应键盘,还可以响应设备的菜单.键盘事件是EventKeyboard,对应的键盘事件监听器(cc.EventList ...