我的问题简而言之:
我有一个WPF TextBox,只允许用户输入十进制数字。我在TextBox的PreviewTextInput事件处理程序中有我的验证逻辑。
我尝试过这样的票价:
使用TryParse
double number = 0;
bool isSuccessful = double.TryParse(e.Text, out number);
e.Handled = !(number >= 0 && isSuccessful);
使用正则表达式:(as per Justin Morgan's response to this question)
string validNumberFormat = @"^[-+]?(\d{1,3}((,\d{3})*(\.\d+)?|([.\s]\d{3})*(,\d+)?)|\d+([,\.]\d+)?)$";
e.Handled = Regex.Matches(e.Text, validNumberFormat).Count < 1;
上述两种方法只允许我输入数字,但不能输入单个小数点。
欢迎任何建议。
答案 0 :(得分:2)
使用行为(Blend SDK System.Windows.Interactivity)而不是直接处理PreviewTextInput。我这样做是因为可重用性,而且你应该知道空间不是用TextInput处理的,而且还没有处理Pasting。顺便说一下,关于你的“小数点”问题,Jonathan和Felice Pollano是对的。
public class TextBoxInputBehavior : Behavior<TextBox>
{
public TextBoxInputMode InputMode { get; set; }
public TextBoxInputBehavior()
{
this.InputMode = TextBoxInputMode.None;
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PreviewTextInput += AssociatedObjectPreviewTextInput;
AssociatedObject.PreviewKeyDown += AssociatedObjectPreviewKeyDown;
DataObject.AddPastingHandler(AssociatedObject, Pasting);
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PreviewTextInput -= AssociatedObjectPreviewTextInput;
AssociatedObject.PreviewKeyDown -= AssociatedObjectPreviewKeyDown;
DataObject.RemovePastingHandler(AssociatedObject, Pasting);
}
private void Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
var pastedText = (string)e.DataObject.GetData(typeof(string));
if(!this.IsValidInput(this.GetText(pastedText)))
{
System.Media.SystemSounds.Beep.Play();
e.CancelCommand();
}
}
else
{
System.Media.SystemSounds.Beep.Play();
e.CancelCommand();
}
}
private void AssociatedObjectPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
if (!this.IsValidInput(this.GetText(" ")))
{
System.Media.SystemSounds.Beep.Play();
e.Handled = true;
}
}
}
private void AssociatedObjectPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!this.IsValidInput(this.GetText(e.Text)))
{
System.Media.SystemSounds.Beep.Play();
e.Handled = true;
}
}
private string GetText(string input)
{
var txt = this.AssociatedObject;
var realtext = txt.Text.Remove(txt.SelectionStart, txt.SelectionLength);
var newtext = realtext.Insert(txt.CaretIndex, input);
return newtext;
}
private bool IsValidInput(string input)
{
switch (InputMode)
{
case TextBoxInputMode.None:
return true;
case TextBoxInputMode.DigitInput:
return input.CheckIsDigit();
case TextBoxInputMode.DecimalInput:
//minus einmal am anfang zulässig
if (input == "-")
return true;
decimal d;
return decimal.TryParse(input, out d);
default: throw new ArgumentException("Unknown TextBoxInputMode");
}
return true;
}
}
public enum TextBoxInputMode
{
None,
DecimalInput,
DigitInput
}
使用
<TextBox>
<i:Interaction.Behaviors>
<MyBehaviors:TextBoxInputBehavior InputMode="DecimalInput"/>
</i:Interaction.Behaviors>
</TextBox>
答案 1 :(得分:0)