WPF TextBox 仅允许输入数字
因为在 IValueConverter 实现中,当文本不能转换为目标类型时返回 DependencyProperty.UnsetValue ,Validation.GetHasError 返回 true ,为何要绕一个圈让用户输入不能转换的文本,然后再获取错误状态呢?不如直接不让用户输入错误文本,于是写了一个 Behavior 派生类:
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;
using System.Windows.Interactivity; namespace WpfApplication6
{
public class OnlyDigitalBehavior : Behavior<TextBox>
{
public Type DigitalType
{
get { return (Type)GetValue(DigitalTypeProperty); }
set { SetValue(DigitalTypeProperty, value); }
} public static readonly DependencyProperty DigitalTypeProperty =
DependencyProperty.Register("DigitalType", typeof(Type), typeof(OnlyDigitalBehavior), new PropertyMetadata()); protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.PreviewTextInput += AssociatedObject_PreviewTextInput;
DataObject.AddPastingHandler(this.AssociatedObject, AssociatedObject_Pasting);
InputMethod.SetIsInputMethodEnabled(this.AssociatedObject, false);
} private void AssociatedObject_Pasting(object sender, DataObjectPastingEventArgs e)
{
e.CancelCommand();
} protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.PreviewTextInput -= AssociatedObject_PreviewTextInput;
DataObject.RemovePastingHandler(this.AssociatedObject, AssociatedObject_Pasting);
} private void AssociatedObject_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
TextBox textBox = sender as TextBox;
Type digitalType = this.DigitalType;
if (textBox == null)
{
return;
}
if (digitalType == typeof(Int16))
{
Int16 i = ;
if (Int16.TryParse(textBox.Text + e.Text, out i))
{
return;
}
}
else if (digitalType == typeof(Int32))
{
Int32 i = ;
if (Int32.TryParse(textBox.Text + e.Text, out i))
{
return;
}
}
else if (digitalType == typeof(Int64))
{
Int64 i = ;
if (Int64.TryParse(textBox.Text + e.Text, out i))
{
return;
}
}
else if (digitalType == typeof(double))
{
double d = ;
if (double.TryParse(textBox.Text + e.Text, out d))
{
return;
}
}
else if (digitalType == typeof(decimal))
{
decimal d = ;
if (decimal.TryParse(textBox.Text + e.Text, out d))
{
return;
}
}
e.Handled = true;
}
}
}
InputMethod.SetIsInputMethodEnabled(this.AssociatedObject, false); 作用是屏蔽输入法。
以下是测试View:
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:WpfApplication6"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock Margin="3">Int16</TextBlock>
<TextBox Margin="3">
<i:Interaction.Behaviors>
<local:OnlyDigitalBehavior DigitalType="{x:Type sys:Int16}" />
</i:Interaction.Behaviors>
</TextBox>
<TextBlock Margin="3">Int32</TextBlock>
<TextBox Margin="3">
<i:Interaction.Behaviors>
<local:OnlyDigitalBehavior DigitalType="{x:Type sys:Int32}" />
</i:Interaction.Behaviors>
</TextBox>
<TextBlock Margin="3">Int64</TextBlock>
<TextBox Margin="3">
<i:Interaction.Behaviors>
<local:OnlyDigitalBehavior DigitalType="{x:Type sys:Int64}" />
</i:Interaction.Behaviors>
</TextBox>
<TextBlock Margin="3">Double</TextBlock>
<TextBox Margin="3">
<i:Interaction.Behaviors>
<local:OnlyDigitalBehavior DigitalType="{x:Type sys:Double}" />
</i:Interaction.Behaviors>
</TextBox>
<TextBlock Margin="3">Decimal</TextBlock>
<TextBox Margin="3">
<i:Interaction.Behaviors>
<local:OnlyDigitalBehavior DigitalType="{x:Type sys:Decimal}" />
</i:Interaction.Behaviors>
</TextBox>
</StackPanel>
</Window>
如果大家有更好的实现方法欢迎赐教!
再来一个支持粘贴的:
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;
using System.Windows.Interactivity; namespace WpfApplication6
{
public class OnlyDigitalBehavior : Behavior<TextBox>
{
private string lastRight = null; public Type DigitalType
{
get { return (Type)GetValue(DigitalTypeProperty); }
set { SetValue(DigitalTypeProperty, value); }
} public static readonly DependencyProperty DigitalTypeProperty =
DependencyProperty.Register("DigitalType", typeof(Type), typeof(OnlyDigitalBehavior), new PropertyMetadata()); protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.TextChanged += AssociatedObject_TextChanged;
InputMethod.SetIsInputMethodEnabled(this.AssociatedObject, false);
} protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.TextChanged -= AssociatedObject_TextChanged;
} private void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
Type digitalType = this.DigitalType;
if (textBox == null)
{
return;
}
if ((IsDigital(digitalType,textBox.Text) || string.IsNullOrEmpty(textBox.Text)) && lastRight != textBox.Text)
{
lastRight = textBox.Text;
}
else if (textBox.Text != lastRight)
{
textBox.Text = lastRight;
textBox.SelectionStart = textBox.Text.Length;
}
} private bool IsDigital(Type targetType,string digitalString)
{
if (targetType == typeof(Int16))
{
Int16 i = ;
if (Int16.TryParse(digitalString, out i))
{
return true;
}
}
else if (targetType == typeof(Int32))
{
Int32 i = ;
if (Int32.TryParse(digitalString, out i))
{
return true;
}
}
else if (targetType == typeof(Int64))
{
Int64 i = ;
if (Int64.TryParse(digitalString, out i))
{
return true;
}
}
else if (targetType == typeof(double))
{
double d = ;
if (double.TryParse(digitalString, out d))
{
return true;
}
}
else if (targetType == typeof(decimal))
{
decimal d = ;
if (decimal.TryParse(digitalString, out d))
{
return true;
}
}
return false;
}
}
}
WPF TextBox 仅允许输入数字的更多相关文章
- c# TextBox只允许输入数字,禁用右键粘贴,允许Ctrl+v粘贴数字
TextBox只允许输入数字,最大长度为10 //TextBox.ShortcutsEnabled为false 禁止右键和Ctrl+v private void txtNumber_KeyPress( ...
- 2019-3-22c# TextBox只允许输入数字,禁用右键粘贴,允许Ctrl+v粘贴数字
TextBox 禁止复制粘贴 ShortcutsEnabled =false TextBox只允许输入数字,最大长度为10 //TextBox.ShortcutsEnabled为false 禁止右键和 ...
- C#的winform中控制TextBox中只能输入数字
C#的winform中控制TextBox中只能输入数字 private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPr ...
- C#中设置TextBox控件中仅可以输入数字且设置上限
首先设置只可以输入数字: 首先设置TextBox控件的KeyPress事件:当用户按下的键盘的键不在数字位的话,就禁止输入 private void textBox1_KeyPress(object ...
- 04实现累加和计算功能并且实现textbox不允许输入数字以外的字符但不包括退格键同时不允许第一个数值为0
private void button1_Click(object sender, EventArgs e) { double number1, number2; if (double.TryPars ...
- C#-WinForm-Winform TextBox中只能输入数字的几种常用方法(C#)
方法一: private void tBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 0x20) e.KeyCh ...
- Winform TextBox中只能输入数字的几种常用方法(C#)
方法一: private void tBox_KeyPress(object sender, KeyPressEventArgs e) { ; //禁止空格键 )) return; //处理负数 if ...
- winform中如何在TextBox中只能输入数字(可以带小数点)
可以采用像web表单验证的方式,利用textbox的TextChanged事件,每当textbox内容变化时,调用正则表达式的方法验证,用一个label在text后面提示输入错误,具体代码如下: pr ...
- input输入框限制仅能输入数字且规定数字长度(使用与输入手机号)
现在越来越多的账户名使用手机号来登录,为了减少前后端的交互,需要用户在输入时就要进行格式的判断, 目前的常规办法是,在输入完成后进行判断. 下面的方法是在输入时就规定只能输入数字,其他格式的字符是无法 ...
随机推荐
- js 输入框只能输入 1-7 的数字
$jq(function () { $jq("#XSCM_WORKDAY").keyup(function () { //如果输入非数字,则替换为'',如果输入数字,则在每4位之后 ...
- Ubuntu网卡设置:配置/etc/netplan
对于Ubuntu1804版本,经过测试如下配置可以设置静态IP地址: Google@ubuntu:~$ cat /etc/netplan/01-netcfg.yaml network: etherne ...
- 44.bucket filter:统计各品牌最近一个月的平均价格
课程大纲 GET /tvs/sales/_search { "size": 0, "query": { "term": { &quo ...
- 仿探探卡片滑动vue封装并发布到npm
项目初始化使用 webpack-simple 方式比较方便和容易配置,原来的方式各种坑慎入 vue init webpack-simple vue-card-slide cd vue-card-sli ...
- 【3】数据筛选2 - requests
目录 1.概述 2.下载安装 3.入门程序 4.请求对象:请求方式 5.请求对象:GET参数传递 6.请求对象:POST参数传递 7.请求对象: ...
- 第八节:numpy之四则运算与逻辑运算
- sql 语句实现可用户名、邮箱、手机号登录系统
select top 1 nid from Users where (userName collate Chinese_PRC_CS_AS=@userName or mobile collate Ch ...
- CodeForcesGym 100735B Retrospective Sequence
Retrospective Sequence Time Limit: Unknown ms Memory Limit: 65536KB This problem will be judged on C ...
- SCU Right turn
Right turn frog is trapped in a maze. The maze is infinitely large and divided into grids. It also c ...
- hibernate 中映射关系配置
多对多 : 外键维护权,一方放弃inverse="true",并且不放弃维护权的一方,加入 cascade="save-update":推荐方案 Student ...