標籤:str catch hand 表達 wpf cas textinput regex length
原文地址
http://blog.csdn.net/ghosind/article/details/51627601
作者 ghosind
一,Regex過濾字串
if (RegexString == null){ switch (ConstraintType) { case RestrictType.Int: // 整數 RegexString = @"^[-]?([\d]+)?$"; break; case RestrictType.UInt: // 非負整數 RegexString = @"^[\d]+$"; break; case RestrictType.Double: // 浮點數 RegexString = @"^[-]?([0-9]+)?[.]?([0-9]+)?$"; break; case RestrictType.UDouble: // 正非負浮點數 RegexString = @"^[0-9]+[.]?([0-9]+)?$"; break; case RestrictType.None: // 無限制 default: RegexString = ""; break; }}
二,PreviewTextInput事件 擷取textbox 的完整文本,(正常textbox.text是輸入前的文本)
if (!Regex.IsMatch(this.Text + e.Text, RegexString)){ e.Handled = true;}
但是如果不是在最後方輸入 直接加起來就不行了,這裡用到CareIndex屬性,(當前游標的位置)
if (!Regex.IsMatch(this.Text.Insert(this.CaretIndex, e.Text), RegexString)){ e.Handled = true;}
但是如果選中一段文字再輸入,結果仍然是錯誤的,所以原作者又用了一個屬性SelectionLength,選擇文本的長度
最終得到輸入後的所有文本的方法終於實現,
private void PreviewTextInput(object sender, TextCompositionEventArgs e){ try { if (!Regex.IsMatch(this.Text.Remove(this.CaretIndex, this.Text.Length >= this.CaretIndex + this.SelectionLength ? this.SelectionLength : 0). Insert(this.CaretIndex, e.Text), RegexString)) { e.Handled = true; } } catch (Exception) { }}
三,用Regex過濾輸入文本,這個網上資料多得很就不抄了,向原作者致敬
WPF開發之限制輸入的控制項---------轉自CDSN