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属性可以切换控件状态. 先看基本样 ...
随机推荐
- Dedecms调用文章发布时间的方法
在织梦系统中,有时候需要调用文章发布的时间,格式不同,代码不同.现总结织梦系统dedecms调用文章发布时间的几种方法. 11-20 样式 ([field:pubdate function='st ...
- Linux常用操作练习
Linux常用操作练习 练习一:安装CentOS 1.设置为1G内存(才有图形界面).10G硬盘 2.分给交换分区2G(4G一下2G,8G-32G分4G-8G) 练习二:安装CentOS迷你版 1.安 ...
- c#中去掉字符串空格方法
(1)Trim方法 string tt=" aaa "; tt=tt.Trim() 去字符串首尾空格的函数 tt=tt.TrimEnd() 去掉字符串尾空格 tt= ...
- photoshop mac版下载及破解
1.下载 直接百度photoshop,就可以找到百度的下载源: 2.破解 http://zhidao.baidu.com/question/581955095.html
- leetcode修炼之路——387. First Unique Character in a String
最近公司搬家了,有两天没写了,今天闲下来了,继续开始算法之路. leetcode的题目如下: Given a string, find the first non-repeating characte ...
- C++ 异常处理执行过程
看<clean code>时,又遇到异常处理的例程. 看不明白是因为我一直都将异常处理束之高阁. 今天晚上下决心去找资料看看,看完之后觉得以前是把它想得太难,其实非常简单. 希望以后遇到问 ...
- 人民币符号¥在css和html正确显示
商城项目需要涉及到人民币的页面现实问题.但是¥(指的是通常输入法中文全角模式下按shift+4的那个)在宋体(v3.03, v5.0)的情况下是显示一杠.常见的其他字体微软雅黑(Microsoft Y ...
- grails-MappingException: Could not determine Type
在用grails的时候遇到这个问题,反复调试了很久,没有进展,同时敲了几个命令后好了,真纠结,这是框架的问题吗? 问题: Caused by MappingException: Could not d ...
- python学习第十八天 --文件操作
这一章节主要讲解文件操作及其文件读取,缓存,文件指针. 文件操作 (1)文件打开:open(filepath,filemode) filepath:要打开文件的路径 filemode:文件打开的方式 ...
- C语言字符串操作函数整理
整理C语言字符串相关的函数,以程序方式验证,以注释方式做说明. #include<stdio.h> #include<string.h> #include<stdlib. ...