2014-12-02 79 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事件(对于空格键)和粘贴事件