0
我想爲TextBox創建樣式,以便它只接受數字,不接受字符或特殊符號。如何在XAML中創建TextBox樣式,以便TextBox只接受數字
目前,我用回代碼的幫助(在C#)喜歡這樣做:
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
是否有可能使XAML的風格來處理這種情況?
我想爲TextBox創建樣式,以便它只接受數字,不接受字符或特殊符號。如何在XAML中創建TextBox樣式,以便TextBox只接受數字
目前,我用回代碼的幫助(在C#)喜歡這樣做:
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
是否有可能使XAML的風格來處理這種情況?
這僅僅是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事件(對於空格鍵)和粘貼事件