2014-12-02 76 views

回答

0

這僅僅是XAML不可能實現的。根據我的經驗,最好的做法是從TextBox派生出來,爲任何可以輸入文本的處理器添加處理程序,然後在文本進入時驗證文本。要麼通過處理事件來拒絕更改,要麼通過讓路由事件傳播。

一般的基類會是什麼樣子:

public abstract class RestrictedTextBox : TextBox 
{ 
    protected RestrictedTextBox() 
    { 
     PreviewTextInput += RestrictedTextBox_PreviewTextInput; 
    } 

    protected abstract bool IsValid(string proposed); 

    private void RestrictedTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) 
    { 
     string proposed = GetProposedText(e.Text); 

     if (!IsValid(proposed)) 
      e.Handled = true; 
    } 

    private string GetProposedText(string newText) 
    { 
     var text = this.Text; 
     if (SelectionStart != -1) 
      text.Remove(this.SelectionStart, this.SelectionLength); 

     return text.Insert(this.CaretIndex, newText); 
    } 
} 

要創建一個具體的例子,讓我們說,一個DoubleTextBox,你可以很容易做到:

public class DoubleTextBox : RestrictedTextBox 
{ 
    protected override bool IsValid(string proposed) 
    { 
     double throwAwayDouble; 
     return double.TryParse(proposed, out throwAwayDouble); 
    } 
} 

這隻會讓你輸入成功解析爲雙精度的文本。我會把它留給你來處理keydown事件(對於空格鍵)和粘貼事件