簡體   English   中英

文本框PreviewTextInput-僅接受數字和':'

[英]Textbox PreviewTextInput - accept only numbers and ':'

我有以下代碼:

foreach (char ch in e.Text)
        {
            if (!Char.IsDigit(ch))
                e.Handled = true;
            else
            {
                if(!(ch.Equals(':')))
                    e.Handled = true;
            }
        }

當只有

if (!Char.IsDigit(ch))
                e.Handled = true;

我可以寫數字,當我只使用第二個if()時,我只能寫':'。 但是當我同時使用它們時,我什么也寫不出來。

只需使用布爾邏輯:

foreach(var ch in e.Text) {
  if (!((Char.IsDigit(ch) || ch.Equals(':'))) {
    e.Handled = true;

    break; 
  }
}

另一種方法是使用linq語句。 它取決於個人喜好,但許多人發現linq更具可讀性。

e.Handled = !e.Text.Any(x => Char.IsDigit(x) || ':'.Equals(x));

這是一個相當簡單的代碼,隨着c#6的到來,整個方法可以編寫為lambda函數,如下所示:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) =>
    e.Handled = !e.Text.Any(x => Char.IsDigit(x) || ':'.Equals(x));

請記住,PreviewTextInput不處理空格字符,並且這些方法不會將其過濾掉。 MSDN論壇上提供了解釋

由於某些IME會將空格擊鍵視為文本編寫過程的一部分,因此Avalon會吃掉它以通過TextInput事件報告正確的合成文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM