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