页面代码:
<UserControl x:Class="AFC.WS.UI.CommonControls.TextBoxExtend"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:AFC.WS.UI.CommonControls"
Name="TextBoxValidizor">
<UserControl.Resources>
<SolidColorBrush x:Key="BackgroundBrush" Color="#FF202020" />
<!-- border style -->
<Style x:Key="BorderStyle" TargetType="{x:Type Border}">
<Setter Property="BorderBrush" Value="{DynamicResource BackgroundBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="3" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" />
</Style>
<!-- textbox style -->
<Style x:Key="TextStyle" TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="2,1,2,2" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="{x:Null}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Stretch" />
</Style>
</UserControl.Resources>
<!-- filter control -->
<Border Name="border" >
<DockPanel>
<my:ValidateImage DockPanel.Dock="Right" x:Name="ValidizorImage"
ToolTip="{Binding ElementName=TextBoxValidizor, Path=ErrorText}" ToolTipService.InitialShowDelay="0" ToolTipService.ShowDuration="60000"/>
<TextBox x:Name="textBox" InputMethod.PreferredImeState="Off" DockPanel.Dock="Left" CommandManager.PreviewExecuted="textBox_PreviewExecuted" />
</DockPanel>
</Border>
</UserControl>
。CS文件代码如下:
#region [ Copyright (C), 2009, 中软AFC, Token Shen. ]
/************************************************************
FileName: TextBoxExtend.xaml
Author: 沈克涛
Version : 1.0
Date:20090715
Description: 文本框的扩展实现
Function List:
1. SetTextBoxDataType(Control ctrl, TextBoxDataType value) // ---> 设置验证的类型
2. FocusEvent(object sender, TextBoxDataType dataType, string message) // ---> 失去焦点时调用的事件
History:
<author> <time> <version > <desc>
沈克涛 2009/07/15 1.0 增加代码说明
* ***********************************************************/
#endregion
#region [ Using namespaces ]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Threading;
using AFC.WS.UI.Common;
using System.Runtime.InteropServices;
#endregion
namespace AFC.WS.UI.CommonControls
{
#region [ TextBoxValidateType ]
/// <summary>
/// 文本框内容类型
/// </summary>
public enum TextBoxDataType
{
/// <summary>
/// 无限制(即混合型)
/// </summary>
None,
/// <summary>
/// 全数字
/// </summary>
AllNumbers,
/// <summary>
/// 十六进制
/// </summary>
Hex,
/// <summary>
/// 金额验证
/// </summary>
Amount,
/// <summary>
/// 所有有理数
/// </summary>
RationalNumericValue,
/// <summary>
/// 字母或数字
/// </summary>
LetterOrDigit,
/// <summary>
/// 汉字或字母或数字
/// </summary>
ChineseOrLetterOrDigit,
/// <summary>
/// 全字母
/// </summary>
AllLetters,
/// <summary>
/// 全大写字母
/// </summary>
AllCapitalLetters,
/// <summary>
/// 全小写字母
/// </summary>
AllLowercaseLetters,
/// <summary>
/// 邮箱
/// </summary>
Email,
/// <summary>
/// IP地址
/// </summary>
IPAddress,
/// <summary>
/// 日期
/// </summary>
Date,
/// <summary>
/// 时间
/// </summary>
Time,
/// <summary>
/// 身份证
/// </summary>
IdentityCard, //@"/d{17}[/d|X]|/d{15}";
/// <summary>
/// 邮政编码
/// </summary>
PastalCode, //expression = @"/d{6}";
/// <summary>
/// MAC地址 //Mac地址正则:[0-9A-F][0-9A-F]-[0-9A-F][0-9A-F]-[0-9A-F][0-9A-F]-[0-9A-F][0-9A-F]-[0-9A-F][0-9A-F]-[0-9A-F][0-9A-F]
/// </summary>
MacIP,
/// <summary>
/// 自定义正则表达式,需要在RegularExpression属性添加正则表达式
/// </summary>
UserDefinedExpression
}
#endregion
/// <summary>
/// TextBoxExtend.xaml 的交互逻辑
/// </summary>
public partial class TextBoxExtend : UserControl, ICommonEdit
{
#region [ Declarations ]
/// <summary>
/// 获取键盘某键的状态
/// </summary>
/// <param name="keyCode"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
/// <summary>
/// 创建接口变量
/// </summary>
private IValueConverter createValueClassInstance = null;
#endregion
#region [ Constructor ]
/// <summary>
/// 够着函数
/// </summary>
public TextBoxExtend()
{
InitializeComponent();
ValidizorImage.Visibility = Visibility.Collapsed;
this.textBox.Loaded += new RoutedEventHandler(textBox_Loaded);
this.textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged);
InputMethod.SetIsInputMethodEnabled(this.textBox, false);
this.textBox.AddHandler(TextBoxExtend.KeyDownEvent, new RoutedEventHandler(HandleHandledKeyDown), true);
}
/// <summary>
/// 文本框改变事件。
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">e</param>
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
int count = 0;
if (TextBoxValidate == TextBoxDataType.ChineseOrLetterOrDigit)
{
if (sender is TextBox)
{
TextBox tbe = sender as TextBox;
int length = GetByteLength(tbe.Text);
if (length > this.RegMaxLength)
{
if (count < 1)
{
//this.textBox.Text = stringFormat(tbe.Text, this.RegMaxLength);
SetErrorInfo("输入字符或中文过长!长度最大为:" + this.RegMaxLength);
count++;
}
}
}
}
}
catch (Exception ex)
{
WriteLog.Log_Error(ex.ToString());
}
}
/// <summary>
/// 格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
/// </summary>
/// <param name="str">要格式化处理的字符串</param>
/// <param name="n">返回新的字符串长度</param>
/// <returns>新的字符串</returns>
public string stringFormat(string str, int n)
{
string temp = string.Empty;
if (System.Text.Encoding.Default.GetByteCount(str) <= n) //如果长度比需要的长度n小,返回原字符串
{
return str;
}
else
{
int t = 0;
char[] q = str.ToCharArray();
for (int i = 0; i < q.Length && t < n; i++)
{
if ((int)q[i] >= 0x4E00 && (int)q[i] <= 0x9FA5) //是否汉字
{
temp += q[i];
t += 2;
}
else
{
temp += q[i];
t++;
}
}
return (temp);
}
}
/// <summary>
/// 获取指定长度的字符串
/// </summary>
/// <param name="text">非指定长度的字符串,包括汉字、数字、字母等</param>
/// <returns>指定长度的字符串</returns>
private string GetLengthString(string text)
{
string lenString = null;
try
{
char[] charArray = text.ToCharArray();
int count = 0;
for (int i = 0; i < charArray.Length; i++)
{
int len = GetByteLength(charArray[i].ToString());
count = count + len;
lenString = lenString + charArray[i].ToString();
if (count == this.RegMaxLength)
{
return lenString;
}
}
}
catch (Exception ex)
{
WriteLog.Log_Error(ex.ToString());
}
return lenString;
}
/// <summary>
/// 判断是否为空格键
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">e</param>
private void HandleHandledKeyDown(object sender, RoutedEventArgs e)
{
KeyEventArgs ke = e as KeyEventArgs;
if (ke.Key == Key.Space)
{
if (TextBoxValidate != TextBoxDataType.ChineseOrLetterOrDigit)
{
ke.Handled = false;
this.textBox.Text = string.Empty;
SetErrorInfo("不允许输入空格!");
}
}
//if (ke.Key == Key.ImeModeChange)
//{
// MessageBox.Show("sdfk");
//}
}
#endregion
#region [ Set Style ]
/// <summary>
/// 窗体加载事件。
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">e</param>
private void textBox_Loaded(object sender, RoutedEventArgs e)
{
if (TextBoxValidate == TextBoxDataType.ChineseOrLetterOrDigit)
{
InputMethod.SetIsInputMethodEnabled(this.textBox, true);
InputMethod.SetPreferredImeConversionMode(this.textBox, ImeConversionModeValues.Native);
}
try
{
SetStyle();
}
catch { }
}
/// <summary>
/// 设置宽度和高度,设置TextBox样式。
/// </summary>
private void SetStyle()
{
try
{
if (ControlWidth != 0)
{
this.Width = ControlWidth;
}
else
{
//this.Width = 150;
}
if (ControlHeight != 0)
{
this.Height = ControlHeight;
}
else
{
//this.Height = 23;
}
if (TextBoxStyle != null)
{
Style style = this.FindResource(TextBoxStyle) as Style;
this.textBox.Style = style;
}
else
{
Style style = this.FindResource("TextStyle") as Style;
this.textBox.Style = style;
}
}
catch (Exception ex)
{