如何让TextBox只接受WPF中的数字输入?

我想接受数字和小数点,但没有迹象。 git

我已经使用Windows窗体的NumericUpDown控件和Microsoft的NumericUpDown自定义控件示例查看了示例 。 但到目前为止,彷佛NumericUpDown(WPF支持或不支持)不会提供我想要的功能。 个人应用程序的设计方式,没有人在他们正确的头脑中想要弄乱箭头。 在个人申请中,它们没有任何实际意义。 正则表达式

因此我正在寻找一种简单的方法来使标准的WPF TextBox只接受我想要的字符。 这可能吗? 这是实用的吗? ide


#1楼

咱们能够对文本框更改事件进行验证。 如下实现可防止除数字和一个小数点之外的按键输入。 wordpress

private void textBoxNumeric_TextChanged(object sender, TextChangedEventArgs e) 
{         
      TextBox textBox = sender as TextBox;         
      Int32 selectionStart = textBox.SelectionStart;         
      Int32 selectionLength = textBox.SelectionLength;         
      String newText = String.Empty;         
      int count = 0;         
      foreach (Char c in textBox.Text.ToCharArray())         
      {             
         if (Char.IsDigit(c) || Char.IsControl(c) || (c == '.' && count == 0))             
         {                 
            newText += c;                 
            if (c == '.')                     
              count += 1;             
         }         
     }         
     textBox.Text = newText;         
     textBox.SelectionStart = selectionStart <= textBox.Text.Length ? selectionStart :        textBox.Text.Length;     
}

#2楼

添加一个VALIDATION RULE,以便在文本更改时检查以肯定数据是否为数字,若是是,则容许继续处理,若是不是,则提示用户该字段仅接受数字数据。 this

阅读Windows Presentation Foundation中的验证 spa


#3楼

添加预览文本输入事件。 像这样: <TextBox PreviewTextInput="PreviewTextInput" />设计

而后在内部设置e.Handled若是不容许文本。 e.Handled = !IsTextAllowed(e.Text); code

我在IsTextAllowed方法中使用一个简单的正则表达式来查看我是否应该容许他们输入的内容。 在个人状况下,我只想容许数字,点和破折号。 orm

private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
    return !_regex.IsMatch(text);
}

若是你想防止不正确的数据粘贴挂钩的DataObject.Pasting事件DataObject.Pasting="TextBoxPasting"在这里 (代码摘录): xml

// Use the DataObject.Pasting Handler 
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        String text = (String)e.DataObject.GetData(typeof(String));
        if (!IsTextAllowed(text))
        {
            e.CancelCommand();
        }
    }
    else
    {
        e.CancelCommand();
    }
}

#4楼

事件处理程序正在预览文本输入。 这里正则表达式只有在不是数字的状况下才匹配文本输入,而后它不会进入文本框。

若是只想要字母,则将正则表达式替换为[^a-zA-Z]

XAML

<TextBox Name="NumberTextBox" PreviewTextInput="NumberValidationTextBox"/>

XAML.CS文件

using System.Text.RegularExpressions;
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}

#5楼

我正在使用一个未绑定的框来处理我正在处理的简单项目,因此我没法使用标准绑定方法。 所以,我建立了一个简单的hack,经过简单地扩展示有的TextBox控件,其余人可能会以为很是方便:

namespace MyApplication.InterfaceSupport
{
    public class NumericTextBox : TextBox
    {


        public NumericTextBox() : base()
        {
            TextChanged += OnTextChanged;
        }


        public void OnTextChanged(object sender, TextChangedEventArgs changed)
        {
            if (!String.IsNullOrWhiteSpace(Text))
            {
                try
                {
                    int value = Convert.ToInt32(Text);
                }
                catch (Exception e)
                {
                    MessageBox.Show(String.Format("{0} only accepts numeric input.", Name));
                    Text = "";
                }
            }
        }


        public int? Value
        {
            set
            {
                if (value != null)
                {
                    this.Text = value.ToString();
                }
                else 
                    Text = "";
            }
            get
            {
                try
                {
                    return Convert.ToInt32(this.Text);
                }
                catch (Exception ef)
                {
                    // Not numeric.
                }
                return null;
            }
        }
    }
}

显然,对于浮动类型,您可能但愿将其解析为浮点数等等。 一样的原则适用。

而后在XAML文件中,您须要包含相关的命名空间:

<UserControl x:Class="MyApplication.UserControls.UnParameterisedControl"
             [ Snip ]
             xmlns:interfaceSupport="clr-namespace:MyApplication.InterfaceSupport"
             >

以后,您能够将其用做常规控件:

<interfaceSupport:NumericTextBox Height="23" HorizontalAlignment="Left" Margin="168,51,0,0" x:Name="NumericBox" VerticalAlignment="Top" Width="120" >
相关文章
相关标签/搜索