如何在silverlight中创建xaml文本框只接受最多一位小数点精度的数字。我在这个问题How to make a textBox accept only Numbers and just one decimal point in Windows 8中尝试了答案。但它没有用。我怎么能这样做?
答案 0 :(得分:1)
你可以写一个这样的函数,
txtDiscount.KeyDown += new KeyEventHandler(EnsureNumbers);
//仅允许数字的方法,
void EnsureNumbers(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
return;
}
bool result = EnsureDecimalPlaces();
if (result == false)
{
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
else
{
e.Handled = true;
}
}
确保只有1位小数的方法,
bool EnsureDecimalPlaces()
{
string inText = txtDiscount.Text;
int decPointIndex = inText.IndexOf('.');
if (decPointIndex < 1 || decPointIndex == 1)
{
return false;
}
else
return true;
}