WPF自定义控件(二)——TextBox

时间:2022-02-04 01:57:05

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

  WPF自定义控件(二)——TextBox

  这个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项目了!

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

  有疑问的多留言哟!