1. 程式人生 > >Silverlight限制TextBox只能輸入整數或者小數

Silverlight限制TextBox只能輸入整數或者小數

  1 ///<summary>  2 /// TextBox篩選行為,過濾不需要的按鍵
  3 ///</summary>  4 publicclass TextBoxFilterBehavior : Behavior<TextBox>  5     {
  6 privatestring _prevText =string.Empty;
  7   8 public TextBoxFilterBehavior()
  9         {
 10         }
 11  12 #region Dependency Properties 13  14 ///<summary>
 15 /// TextBox篩選選項,這裡選擇的為過濾後剩下的按鍵
 16 /// 控制鍵不參與篩選,可以多選組合
 17 ///</summary> 18 public TextBoxFilterOptions TextBoxFilterOptions
 19         {
 20 get { return (TextBoxFilterOptions)GetValue(TextBoxFilterOptionsProperty); }
 21 set { SetValue(TextBoxFilterOptionsProperty, value); }
 22         }
 23
  24 // Using a DependencyProperty as the backing store for TextBoxFilterOptions.  This enables animation, styling, binding, etc... 25 publicstaticreadonly DependencyProperty TextBoxFilterOptionsProperty = 26             DependencyProperty.Register("TextBoxFilterOptions"typeof(TextBoxFilterOptions), 
typeof(TextBoxFilterBehavior), new PropertyMetadata(TextBoxFilterOptions.None));
 27  28 #endregion 29  30 protectedoverridevoid OnAttached()
 31         {
 32 base.OnAttached();
 33  34 this.AssociatedObject.KeyDown +=new KeyEventHandler(AssociatedObject_KeyDown);
 35 this.AssociatedObject.TextChanged +=new TextChangedEventHandler(AssociatedObject_TextChanged);
 36         }
 37  38 protectedoverridevoid OnDetaching()
 39         {
 40 base.OnDetaching();
 41  42 this.AssociatedObject.KeyDown -=new KeyEventHandler(AssociatedObject_KeyDown);
 43 this.AssociatedObject.TextChanged -=new TextChangedEventHandler(AssociatedObject_TextChanged);
 44         }
 45  46 #region Events 47  48 ///<summary> 49 /// 處理通過其它手段進行的輸入
 50 ///</summary> 51 ///<param name="sender"></param> 52 ///<param name="e"></param> 53 void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
 54         {
 55 //如果符合規則,就儲存下來 56 if (IsValidText(this.AssociatedObject.Text))
 57             {
 58                 _prevText =this.AssociatedObject.Text;
 59             }
 60 //如果不符合規則,就恢復為之前儲存的值 61 else 62             {
 63 int selectIndex =this.AssociatedObject.SelectionStart - (this.AssociatedObject.Text.Length - _prevText.Length);                
 64 this.AssociatedObject.Text = _prevText;
 65 this.AssociatedObject.SelectionStart = selectIndex;
 66             }
 67  68         }
 69  70 ///<summary> 71 /// 處理按鍵產生的輸入
 72 ///</summary> 73 ///<param name="sender"></param> 74 ///<param name="e"></param> 75 void AssociatedObject_KeyDown(object sender, KeyEventArgs e)
 76         {
 77 bool handled =true;
 78 //不進行過濾 79 if (TextBoxFilterOptions == TextBoxFilterOptions.None || 80                 KeyboardHelper.IsControlKeys(e.Key))
 81             {
 82                 handled =false;
 83             }
 84 //數字鍵 85 if (handled && TextBoxFilterOptions.ContainsOption(TextBoxFilterOptions.Numeric))
 86             {
 87                 handled =!KeyboardHelper.IsDigit(e.Key);
 88             }
 89 //小數點 90 if (handled && TextBoxFilterOptions.ContainsOption(TextBoxFilterOptions.Dot))
 91             {
 92                 handled =!(KeyboardHelper.IsDot(e.Key, e.PlatformKeyCode) &&!_prevText.Contains("."));
 93 if (KeyboardHelper.IsDot(e.Key, e.PlatformKeyCode) && _prevText.Contains("."))
 94                 {
 95 //如果輸入位置的下一個就是小數點,則將游標跳到小數點後面 96 if (this.AssociatedObject.SelectionStart<this.AssociatedObject.Text.Length && _prevText[this.AssociatedObject.SelectionStart] =='.')
 97                     {
 98 this.AssociatedObject.SelectionStart++;
 99                     }                    
100                 }
101             }
102 //字母103 if (handled && TextBoxFilterOptions.ContainsOption(TextBoxFilterOptions.Character))
104             {
105                 handled =!KeyboardHelper.IsDot(e.Key);
106             }
107             e.Handled = handled;
108         }
109 110 #endregion111 112 #region Private Methods113 114 ///<summary>115 /// 判斷是否符合規則
116 ///</summary>117 ///<param name="c"></param>118 ///<returns></returns>119 privatebool IsValidChar(char c)
120         {
121 if (TextBoxFilterOptions == TextBoxFilterOptions.None)
122             {
123 returntrue;
124             }
125 elseif (TextBoxFilterOptions.ContainsOption(TextBoxFilterOptions.Numeric) &&126 '0'<= c && c <='9')
127             {
128 returntrue;
129             }
130 elseif (TextBoxFilterOptions.ContainsOption(TextBoxFilterOptions.Dot) &&131                 c =='.')
132             {
133 returntrue;
134             }
135 elseif (TextBoxFilterOptions.ContainsOption(TextBoxFilterOptions.Character)) 
136             {
137 if (('A'<= c && c <='Z'|| ('a'<= c && c <='z'))
138                 {
139 returntrue;
140                 }
141             }
142 returnfalse;
143         }
144 145 ///<summary>146 /// 判斷文字是否符合規則
147 ///</summary>148 ///<param name="text"></param>149 ///<returns></returns>150 privatebool IsValidText(string text)
151         {
152 //只能有一個小數點153 if (text.IndexOf('.'!= text.LastIndexOf('.'))
154             {
155 returnfalse;
156             }
157 158 foreach (char c in text)
159             {
160 if (!IsValidChar(c))
161                 {
162 returnfalse;
163                 }
164             }
165 returntrue;
166         }
167 168 #endregion169     }
170 

相關推薦

Silverlight限制TextBox只能輸入整數或者小數

  1 ///<summary>  2 /// TextBox篩選行為,過濾不需要的按鍵   3 ///</summary>  4 publicclass TextBoxFilterBehavior : Behavior<TextBox>  5     {   6 pr

JS通過正則限制 input 輸入只能輸入整數小數(金額或者現金) 兩位小數

第一: 限制只能是整數 ? 1 <input type = "text" name= "number" id = 'number' onkeyup= "if(! /^d+$/.t

Android限制EditText只能輸入中文或者指定內容的實現

最近專案中要限制EditText中只能輸入中文,之前寫過一個限制EditText只能輸入中文的實現,不過存在一些問題,而且擴充套件性不是很好,所以換了一種方法來實現. 先看一下效果圖: 具體實現 一般對EditText的操作及處理都是用addTex

html限制input框只能輸入數字或小數

前端程式碼: <input type="text" name="payMoney[]" onkeyup="clearNoNum(this)" value=""> js程式碼: <script language="JavaScript" type="t

input限制只能輸入整數或保留小數點後2位的浮點數

1、test.js檔案內容如下:/** * 使用示例: $("#price").decimalinput();//文字框只能輸入2位小數 */ $.fn.decimalinput = function () { $(this).css("ime-mode",

限制input只能輸入數字且限制只能輸入兩位小數

chrome中的input不要加type=”number”,有問題,輸入負號擷取到第一個字串是空,就預設text就行 若允許負數加上allowMinus類,正數只加limitNumber 以下可以封裝成函式,加到DOM上的onkeyup=foo(this)

WPF TextBox 只能輸入數字,並限制輸入大小

                /// <summary>         /// 文字框文字輸入事件         /// </summary>         private void txt_PreviewTextInput(object se

c# 控制TextBox只能輸入小數只能輸入一個小數點,小數點後只能輸入兩位,第一位不能是小數點)

/// <summary> /// 價格和數量輸入控制(只能輸入一個小數點,小數點後只能輸入兩位,第一位不能是小數點) /// </summary> /// <param name="e">

js jquery 限制input輸入只能輸入兩位小數的數字

//正整數 兩位小數 $('.inputWrap').on('input', function () { var num = $(this).val(); if(n

TextBox只能輸入數字

arr .get nbsp tar array end rgs bytes () private void textBox1_KeyPress(object sender, KeyPressEventArgs e){ byte[] array = System.Te

限制input只能輸入數字/數字和小數點

red onkeyup this span replace ice fff round logs 1.限制input只能輸入數字 <input id="Number" name="Number" type="text" class="form-control req

限制前端只能輸入數字

shiy使用onkeyup和onafterpaste事件 在input文字加上這段話 onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')

Asp.net TextBox只能輸入數字

<asp:textbox id="TextBox1" onkeyup="if(isNaN(value))execCommand('undo')" runat="server" Width="80px" onafterpaste="if(isNaN(value))execComman

input 輸入只能輸入數字,長度為2(也可以修改任意長度);input框只能輸入數字或小數

直接放在input標籤裡面 1.input長度為2 oninput="if(value.length>2)value=value.slice(0,2)"  2.控制input輸入數字 onkeyup="if(this.value.length==1){this.v

限制EditText只能輸入中文

MyEditText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(18)});/** * EditText只能輸入中文 */ InputFilter filte

限定EditText只能輸入兩位小數的兩種方式

/** * 限定EditText只能輸入最多兩位小數 * @author Administrator * */ public class MainActivity extends ActionBarActivity { private EditText num_et; private EditT

控制輸入只能輸入兩位小數和一個小數點

在專案中會對輸入框中的輸入值實時控制小數位,限制使用者只能輸入兩位小數,一個小數點.$(obj).bind("input onInput",function(){ var value =

javascript/JS限制使用者名稱只能輸入 漢字字母和數字下劃線

驗證使用者名稱的一個例子: html: js: function checkUser() { var username = $(“#username”).val(); if (!username.match( /^[\u4E00-\u9FA5a

正則匹配只能輸入整數或浮點數

// 只能輸入整數或浮點數(不完全版本不能排除輸入0.00000的狀況) filterNumber(name,e){ //先把非數字的都替換掉,除了數字和. e.

MVVM模式下 所有控制元件共享同一事件 以TextBox只能輸入數字鍵和回車鍵為例子

一:首先對MvvmLight裡的ViewModel進行封裝    封裝完畢後讓ViewModel繼承DialogViewModel  public class DialogViewModel : ViewModelBase     {         public voi