因为在 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 仅允许输入数字的更多相关文章

  1. c# TextBox只允许输入数字,禁用右键粘贴,允许Ctrl+v粘贴数字

    TextBox只允许输入数字,最大长度为10 //TextBox.ShortcutsEnabled为false 禁止右键和Ctrl+v private void txtNumber_KeyPress( ...

  2. 2019-3-22c# TextBox只允许输入数字,禁用右键粘贴,允许Ctrl+v粘贴数字

    TextBox 禁止复制粘贴 ShortcutsEnabled =false TextBox只允许输入数字,最大长度为10 //TextBox.ShortcutsEnabled为false 禁止右键和 ...

  3. C#的winform中控制TextBox中只能输入数字

    C#的winform中控制TextBox中只能输入数字 private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPr ...

  4. C#中设置TextBox控件中仅可以输入数字且设置上限

    首先设置只可以输入数字: 首先设置TextBox控件的KeyPress事件:当用户按下的键盘的键不在数字位的话,就禁止输入 private void textBox1_KeyPress(object ...

  5. 04实现累加和计算功能并且实现textbox不允许输入数字以外的字符但不包括退格键同时不允许第一个数值为0

    private void button1_Click(object sender, EventArgs e) { double number1, number2; if (double.TryPars ...

  6. C#-WinForm-Winform TextBox中只能输入数字的几种常用方法(C#)

    方法一: private void tBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 0x20) e.KeyCh ...

  7. Winform TextBox中只能输入数字的几种常用方法(C#)

    方法一: private void tBox_KeyPress(object sender, KeyPressEventArgs e) { ; //禁止空格键 )) return; //处理负数 if ...

  8. winform中如何在TextBox中只能输入数字(可以带小数点)

    可以采用像web表单验证的方式,利用textbox的TextChanged事件,每当textbox内容变化时,调用正则表达式的方法验证,用一个label在text后面提示输入错误,具体代码如下: pr ...

  9. input输入框限制仅能输入数字且规定数字长度(使用与输入手机号)

    现在越来越多的账户名使用手机号来登录,为了减少前后端的交互,需要用户在输入时就要进行格式的判断, 目前的常规办法是,在输入完成后进行判断. 下面的方法是在输入时就规定只能输入数字,其他格式的字符是无法 ...

随机推荐

  1. Django - 数据获取

    Django - 数据获取 1.radio值获取 2.checkbox获取 3.select 获取 select 获取值,需要根据前端multiple来获取,get or getlist; 4.上传文 ...

  2. B.4 集

    在.NET 3.5之前,框架中根本没有公开集(set)集合.如果要在.NET 2.0中表示集,通常会 使用 Dictionary<,> ,用集的项作为键,用假数据作为值..NET3.5的 ...

  3. php第十七节课

    分页查询 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

  4. JAVA学习总结-基础语法

    /** * 这篇文章供自己学习JAVA总结回顾使用 * 主要借鉴了马士兵老师的视频进行总结 * @author Kingram */ 标识符的概念和命名规则 JAVA常量---不可变的变量 程序的执行 ...

  5. (ccf)201709-4 通信网络

    #include<iostream> #include<memory.h> #include<stack> #include<string> #incl ...

  6. 编写who命令

    第一个版本: /* who1.c - a first version of the who program * open, read UTMP file, and show results. */ # ...

  7. java.lang.ClassFormatError: Unknown constant tag 0 in class file

    在通过文件上传之后,运行java程序,突然发现这么一个错误:java.lang.ClassFormatError: Unknown constant tag 0 in class file,通过网上查 ...

  8. [luogu1156]垃圾陷阱_动态规划_背包dp

    垃圾陷阱 luogu-1156 题目大意:Holsteins在距离地面D英尺的地方,FJ间隔时间ti会往下扔第i个垃圾.Holsteins对待每一个垃圾都会选择吃掉或者垫高.Holsteins有10个 ...

  9. RSA 数据加密和数字签名算法

    PKCS8EncodedKeySpec pkcs8KeySpec = KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Pr ...

  10. 查看OS 各项参数

    查看CPU 在linux下 cat /proc/cpuinfo 可以得到CPU信息. 要注意的是CPU型号有不同的种类比如AMD Intel.可能在这个文件中显示的信息也不同.但终归是存在这个文件中的 ...