如何讓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" >
相關文章
相關標籤/搜索