With the help of Romasz link in his first comment I came up with this solution:
private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
double dtemp;
if (!double.TryParse(sender.Text, out dtemp) && sender.Text != "")
{
int pos = sender.SelectionStart - 1;
sender.Text = sender.Text.Remove(pos, 1);
sender.SelectionStart = pos;
}
}
This works quite fine except when a part of the input value is selected and then a wrong character is entered.
Edit:
I improved the above version to use Regex. So now I'm able to check whatever content should be allowed to enter:
private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
if (!Regex.IsMatch(sender.Text, "^\d*\.?\d*$") && sender.Text != "")
{
int pos = sender.SelectionStart - 1;
sender.Text = sender.Text.Remove(pos, 1);
sender.SelectionStart = pos;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…