WPF自定义数字输入框控件
要求:只能输入数字和小数点,可以设置最大值,最小值,小数点前长度,小数点后长度(支持绑定设置);
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input; namespace MyTool
{
/// <summary>
/// 数字输入框
/// author lixinmiao
/// </summary>
class NumTextBox : TextBox
{
public static readonly DependencyProperty NumTypeProperty = DependencyProperty.Register("NumType", typeof(Type), typeof(NumTextBox));
public static readonly DependencyProperty MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(decimal), typeof(NumTextBox), new FrameworkPropertyMetadata(
new PropertyChangedCallback(CheckProperty))); public static readonly DependencyProperty MinValueProperty = DependencyProperty.Register("MinValue", typeof(decimal), typeof(NumTextBox), new FrameworkPropertyMetadata(
new PropertyChangedCallback(CheckProperty)));
public static readonly DependencyProperty PointLenthProperty = DependencyProperty.Register("PointLenth", typeof(int), typeof(NumTextBox));
public static readonly DependencyProperty NumberLengthProperty = DependencyProperty.Register("NumberLength", typeof(int), typeof(NumTextBox));
// private System.Globalization.CultureInfo cI;
public NumTextBox()
{
MinValue = decimal.MinValue;
MaxValue = decimal.MaxValue;
PointLenth = ;
NumberLength = ; }
public enum Type { Decimal, UDecimal, Int, UInt }
/// <summary>
/// 设置或获取textbox的输入数据类型
/// </summary>
public Type NumType
{
get { return (Type)GetValue(NumTypeProperty); }
set { SetValue(NumTypeProperty, value); }
}
/// <summary>
/// 设定或获取最大值
/// </summary>
public decimal MaxValue
{
get { return (decimal)GetValue(MaxValueProperty); }
set { SetValue(MaxValueProperty, value); }
} /// <summary>
/// 设定或获取最小值
/// </summary>
public decimal MinValue
{
get { return (decimal)GetValue(MinValueProperty); }
set { SetValue(MinValueProperty, value); }
}
/// <summary>
/// 设置或获取小数点前的位数
/// </summary>
public int NumberLength
{
get { return (int)GetValue(NumberLengthProperty); }
set { SetValue(NumberLengthProperty, value); }
}
/// <summary>
/// 设置或获取小数点后位数长度
/// </summary>
public int PointLenth
{
get { return (int)GetValue(PointLenthProperty); }
set { SetValue(PointLenthProperty, value); }
} private string val = "";
/// <summary>
/// 设定最大值最小值依赖属性回调函数
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void CheckProperty(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NumTextBox ntb = d as NumTextBox;
if (ntb.MaxValue < ntb.MinValue)
ntb.MaxValue = ntb.MinValue;
}
/// <summary>
/// 重写KeyDown事件,提供与事件有关的数据,过滤输入数据格式
/// </summary>
/// <param name="e"></param>
protected override void OnKeyDown(KeyEventArgs e)
{
string txt = this.Text;
int ind = this.CaretIndex;
if (txt.Contains("."))
{
// Console.WriteLine(txt.Split('.')[0] + "he " + txt.Split('.')[1]);
if (txt.Split('.')[].Length >= PointLenth && ind > txt.Split('.')[].Length && this.SelectionLength == )//控制小数点后输入位数
{
e.Handled = true;
return;
}
else if (txt.Split('.')[].Length >= NumberLength && ind <= txt.Split('.')[].Length)//控制小数点前输入位数(有小数点)
{
e.Handled = true;
return;
}
}
else if (txt.Length == NumberLength && e.Key != Key.Decimal && e.Key != Key.OemPeriod)//控制小数点前输入位数(无小数点)
{
e.Handled = true;
return;
} if (e.Key == Key.Decimal || e.Key == Key.OemPeriod)
{
val = ".";
}
else
{ val = "";
}
switch (NumType)
{ case Type.UInt:
//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key.ToString() == "Tab")
{
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9)) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
e.Handled = false;
}
else
{
e.Handled = true;
if (e.Key.ToString() != "RightCtrl")
{ }
}
break;
case Type.Int:
//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Subtract || e.Key.ToString() == "Tab")
{
if ((txt.Contains("-") || this.CaretIndex != ) && e.Key == Key.Subtract)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemMinus) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
if ((txt.Contains("-") || this.CaretIndex != ) && e.Key == Key.OemMinus)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else
{
e.Handled = true;
if (e.Key.ToString() != "RightCtrl")
{ }
}
break;
case Type.Decimal:
//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key == Key.Subtract || e.Key.ToString() == "Tab")
{
if (txt.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
return;
}
else if ((txt.Contains("-") || this.CaretIndex != ) && e.Key == Key.Subtract)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod || e.Key == Key.OemMinus) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
if (txt.Contains(".") && e.Key == Key.OemPeriod)
{
e.Handled = true;
return;
}
else if ((txt.Contains("-") || this.CaretIndex != ) && e.Key == Key.OemMinus)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else
{
e.Handled = true;
if (e.Key.ToString() != "RightCtrl")
{ }
}
break;
case Type.UDecimal:
default:
//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key.ToString() == "Tab")
{
if (txt.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
if (txt.Contains(".") && e.Key == Key.OemPeriod)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else
{
e.Handled = true;
if (e.Key.ToString() != "RightCtrl")
{ }
} break;
}
base.OnKeyDown(e);
}
/// <summary>
///粘贴内容过滤,设定最大值、最小值,限制小数点输入长度
/// </summary>
/// <param name="e"></param>
protected override void OnTextChanged(TextChangedEventArgs e)
{
int t1 = this.Text.Length;
if (t1 != )//用于是否可以将文本空置空
{
decimal d = ;
if (this.Text != "-" && this.Text != "." && this.Text != "-0" && this.Text != "-." && this.Text != "-0." && val != ".")
{
if (decimal.TryParse(this.Text, out d))
{
if (NumType == Type.Decimal || NumType == Type.UDecimal)
{
if (d.ToString().Split('.')[].Length > NumberLength)//
{
d = ;
}
else
{
d = Math.Round(d, PointLenth, MidpointRounding.AwayFromZero);
}
}
else
if (d.ToString().Split('.')[].Length > NumberLength)//
{
d = ;
}
else
{
d = Math.Round(d, , MidpointRounding.AwayFromZero);
}
}
int t2 = d.ToString().Length;
if (Math.Abs(t1 - d.ToString().Length) > )
{
this.Text = d.ToString();
this.CaretIndex = d.ToString().Length;
}
else
{
this.Text = d.ToString();
} }
if ((NumType == Type.UDecimal || NumType == Type.UInt) && this.Text.Contains("-"))
{
this.Text = Math.Abs(d).ToString();
}
if ((NumType == Type.UInt || NumType == Type.Int) && this.Text.Contains("."))
{
this.Text = int.Parse(d.ToString()).ToString();
}
}
base.OnTextChanged(e);
} /// <summary>
///如果数据是0,得到光标,清空数据
/// </summary>
/// <param name="e"></param>
protected override void OnGotFocus(RoutedEventArgs e)
{
//InputMethod.SetPreferredImeState(this, InputMethodState.Off);
//cI = InputLanguageManager.GetInputLanguage(this);
//decimal d = 0;
//if (decimal.TryParse(this.Text, out d))
//{
if (this.Text == "")
{
this.Text = "";
}
//}
//else
//{
// this.Text = "";
//}
base.OnGotFocus(e);
} /// <summary>
///失去光标,确定最大值最小值
/// </summary>
/// <param name="e"></param>
protected override void OnLostFocus(RoutedEventArgs e)
{
decimal d = ;
if (decimal.TryParse(this.Text, out d))
{
if (d < MinValue)
{
d = MinValue;
this.Text = d.ToString();
} else if (d > MaxValue)
{
d = MaxValue;
this.Text = d.ToString();
}
}
else if (string.IsNullOrEmpty(this.Text))
{
this.Text = "";
}
else
{
this.Text = d.ToString();
}
base.OnLostFocus(e);
//System.Globalization.CultureInfo cI = InputLanguageManager.GetInputLanguage(this);
//InputMethod.SetPreferredImeState(this, InputMethodState.DoNotCare);
//InputLanguageManager.SetInputLanguage(this, cI);
//cI = null;
}
}
}
具体用法:
将改文件命名控件引用到要使用的xaml页面,然后采用引用控件的使用方法使用即可。
通过NumType设置绑定的数据类型,整数,正整数,小数,正小数;
其余的几个属性类似;
欢迎探讨。
有问题,请联系QQ:2860580831 或发邮件到2860580831@qq.com
WPF自定义数字输入框控件的更多相关文章
- WPF自定义选择年月控件详解
		本文实例为大家分享了WPF自定义选择年月控件的具体代码,供大家参考,具体内容如下 封装了一个选择年月的控件,XAML代码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 
- WPF 自定义DateControl DateTime控件
		自定义日期控件,月份选择.如下是日期的一些效果图. 具体的样式.颜色可以根据下面的代码,自己调节即可 1.日期控件的界面 <UserControl x:Class="WpfApp ... 
- WPF 自定义DateControl DateTime控件(转)
		自定义日期控件,月份选择.如下是日期的一些效果图. 具体的样式.颜色可以根据下面的代码,自己调节即可 1.日期控件的界面 <UserControl x:Class="WpfApp ... 
- WPF自定义DataGrid分页控件
		新建Custom Control,名:PagingDataGrid 打开工程下面的Themes\Generic.xaml xaml里面代码替换如下 <Style x:Key="{x:T ... 
- WPF自定义轮播控件
		闲得蛋疼做了一个WPF制作轮播动画(随机动画),勉强可以看,写个随笔留个脚印. 效果图: 
- WPF自定义下拉控件
		可以搜索的下拉条 using System; using System.Collections; using System.Collections.Generic; using System.Coll ... 
- WPF自定义控件与样式(8)-ComboBox与自定义多选控件MultComboBox
		一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: 下拉选 ... 
- 【转】WPF自定义控件与样式(8)-ComboBox与自定义多选控件MultComboBox
		一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等. 本文主要内容: 下拉选择控件ComboBox的自定义样式及扩展: 自定义多选控件Mul ... 
- WPF 自定义ComboBox样式,自定义多选控件
		原文:WPF 自定义ComboBox样式,自定义多选控件 一.ComboBox基本样式 ComboBox有两种状态,可编辑和不可编辑状态.通过设置IsEditable属性可以切换控件状态. 先看基本样 ... 
随机推荐
- 使用<input>标签做了两个按钮, 按钮之间间距如何去掉
			遇到的问题: 使用<input>标签做了两个按钮, 按钮之间有个间距不知道怎么去掉. 如下图: 问题解决: <input>是内联块状元素(inline-block); 内联元素 ... 
- HTML5 Canvas Text实例1
			1.简单实例1 <canvas width="300" height="300" id="canvasOne" class=" ... 
- 未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序(Oledb)
			转载:http://blog.csdn.net/lemontec/article/details/1754413 前几天用c#读 Excel 出现了如下问题未在本地计算机上注册“Microsoft.J ... 
- c - 字符串的反转
			1,递归实现 // 递归实现字符串反转(可通过栈的调用来加深理解). char * reverse(char *c) { if(!c) return NULL; int len = strlen(c) ... 
- linux 进程数
			一.linux系统支持的最大进程数 限制1:既然系统使用pid_t表示进程号,那么最大进程数不能超过pid_t类型的最大值吧 限制2:使用命令ulimit -u查看系统中限制的最大进程数,我的机器上是 ... 
- Spring4.0学习笔记(6) —— 通过工厂方法配置Bean
			1.静态工厂方法: bean package com.spring.factory; public class Car { public Car(String brand) { this.brand ... 
- JS浮点数运算Bug
			JS浮点数运算Bug的解决办法(转) 37.5*5.5=206.08 (JS算出来是这样的一个结果,我四舍五入取两位小数) 我先怀疑是四舍五入的问题,就直接用JS算了一个结果为:206.0849999 ... 
- js监控键盘大小写事件
			JavaScript键盘事件侦听 在使用JavaScript做WEB键盘事件侦听捕获时,主要采用onkeypress.onkeydown.onkeyup三个事件进行出来.该三个事 件的执行顺序如 ... 
- python urllib2
			http://my.oschina.net/duhaizhang/blog/69883 
- 报错:tr was not declared in this scope
			报错代码如下: label->setText(tr("您好,Qt5.5.0!")); 修改为: label->setText(QObject::tr("您好, ... 
