1. 程式人生 > >C# WPF TextBox控制只能輸入某一範圍(比如0-100)的整數

C# WPF TextBox控制只能輸入某一範圍(比如0-100)的整數

基本原理是直接新增兩個事件,然後加上判斷: 

1. KeyDown 2.TextChanged

話不多說,直接上程式碼:

    前臺程式碼:

<TextBox x:Name="TextBoxForText" HorizontalAlignment="Left" Height="101" Margin="10,167,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="299" KeyDown="TextBoxForText_KeyDown" MaxLength="3" TextChanged="TextBoxForText_TextChanged">

    後臺程式碼:

private void TextBoxForText_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox txt = sender as TextBox;

            // 過濾按鍵
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
            {
                e.Handled = false;
            }
            else if (((e.Key >= Key.D0 && e.Key <= Key.D9)))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }

        }

        private void TextBoxForText_TextChanged(object sender, TextChangedEventArgs e)
        {
            try 
            {
                string strNum = TextBoxForText.Text;
                if ("" == strNum || null == strNum)
                {
                    return;
                }
                int num = int.Parse(TextBoxForText.Text);
                TextBoxForText.Text = num.ToString();
                if (num <= 100)
                {
                    return;
                }
                else
                {
                    TextBoxForText.Text = TextBoxForText.Text.Remove(2);
                    TextBoxForText.SelectionStart = TextBoxForText.Text.Length;
                }
             }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }