我希望接受数字和小数点,但没有符号。
我已经看过使用Windows窗体中的NumericUpDown控件的示例,以及来自微软的这个NumericUpDown自定义控件的示例。但到目前为止,似乎NumericUpDown (WPF是否支持)不会提供我想要的功能。我的应用程序是这样设计的,任何头脑正常的人都不会想弄乱箭头。在我的应用程序中,它们没有任何实际意义。
所以我正在寻找一个简单的方法,使一个标准的WPF文本框只接受我想要的字符。这可能吗?实用吗?
我希望接受数字和小数点,但没有符号。
我已经看过使用Windows窗体中的NumericUpDown控件的示例,以及来自微软的这个NumericUpDown自定义控件的示例。但到目前为止,似乎NumericUpDown (WPF是否支持)不会提供我想要的功能。我的应用程序是这样设计的,任何头脑正常的人都不会想弄乱箭头。在我的应用程序中,它们没有任何实际意义。
所以我正在寻找一个简单的方法,使一个标准的WPF文本框只接受我想要的字符。这可能吗?实用吗?
当前回答
下面的代码创建了一个控件,你将能够像正常的文本框一样使用,但它只会把一个正的双精度作为输入:
在XAML中,你可以这样使用这个控件:
<local:UnsignedDoubleBox/>
在c#代码中,在当前命名空间中添加以下内容:
public class UnsignedDoubleBox : TextBox
{
public UnsignedDoubleBox()
{
this.PreviewTextInput += defaultPreviewTextInput;
DataObject.AddPastingHandler(this, defaultTextBoxPasting);
}
private bool IsTextAllowed(TextBox textBox, String text)
{
//source: https://stackoverflow.com/questions/23397195/in-wpf-does-previewtextinput-always-give-a-single-character-only#comment89374810_23406386
String newText = textBox.Text.Insert(textBox.CaretIndex, text);
double res;
return double.TryParse(newText, out res) && res >= 0;
}
//source: https://stackoverflow.com/a/1268648/13093413
private void defaultTextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed((TextBox)sender, text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
private void defaultPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (IsTextAllowed((TextBox)sender, e.Text))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
}
其他回答
下面的代码创建了一个控件,你将能够像正常的文本框一样使用,但它只会把一个正的双精度作为输入:
在XAML中,你可以这样使用这个控件:
<local:UnsignedDoubleBox/>
在c#代码中,在当前命名空间中添加以下内容:
public class UnsignedDoubleBox : TextBox
{
public UnsignedDoubleBox()
{
this.PreviewTextInput += defaultPreviewTextInput;
DataObject.AddPastingHandler(this, defaultTextBoxPasting);
}
private bool IsTextAllowed(TextBox textBox, String text)
{
//source: https://stackoverflow.com/questions/23397195/in-wpf-does-previewtextinput-always-give-a-single-character-only#comment89374810_23406386
String newText = textBox.Text.Insert(textBox.CaretIndex, text);
double res;
return double.TryParse(newText, out res) && res >= 0;
}
//source: https://stackoverflow.com/a/1268648/13093413
private void defaultTextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed((TextBox)sender, text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
private void defaultPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (IsTextAllowed((TextBox)sender, e.Text))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
}
这是唯一需要的代码:
void MyTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
}
这只允许在文本框中输入数字。
若要允许使用小数点或负号,可以将正则表达式更改为[^0-9.-]+。
我使用了一些已经在这里的东西,并使用一个行为把我自己的扭曲,这样我就不必在大量的视图中传播这段代码……
public class AllowableCharactersTextBoxBehavior : Behavior<TextBox>
{
public static readonly DependencyProperty RegularExpressionProperty =
DependencyProperty.Register("RegularExpression", typeof(string), typeof(AllowableCharactersTextBoxBehavior),
new FrameworkPropertyMetadata(".*"));
public string RegularExpression
{
get
{
return (string)base.GetValue(RegularExpressionProperty);
}
set
{
base.SetValue(RegularExpressionProperty, value);
}
}
public static readonly DependencyProperty MaxLengthProperty =
DependencyProperty.Register("MaxLength", typeof(int), typeof(AllowableCharactersTextBoxBehavior),
new FrameworkPropertyMetadata(int.MinValue));
public int MaxLength
{
get
{
return (int)base.GetValue(MaxLengthProperty);
}
set
{
base.SetValue(MaxLengthProperty, value);
}
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PreviewTextInput += OnPreviewTextInput;
DataObject.AddPastingHandler(AssociatedObject, OnPaste);
}
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(DataFormats.Text))
{
string text = Convert.ToString(e.DataObject.GetData(DataFormats.Text));
if (!IsValid(text, true))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = !IsValid(e.Text, false);
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PreviewTextInput -= OnPreviewTextInput;
DataObject.RemovePastingHandler(AssociatedObject, OnPaste);
}
private bool IsValid(string newText, bool paste)
{
return !ExceedsMaxLength(newText, paste) && Regex.IsMatch(newText, RegularExpression);
}
private bool ExceedsMaxLength(string newText, bool paste)
{
if (MaxLength == 0) return false;
return LengthOfModifiedText(newText, paste) > MaxLength;
}
private int LengthOfModifiedText(string newText, bool paste)
{
var countOfSelectedChars = this.AssociatedObject.SelectedText.Length;
var caretIndex = this.AssociatedObject.CaretIndex;
string text = this.AssociatedObject.Text;
if (countOfSelectedChars > 0 || paste)
{
text = text.Remove(caretIndex, countOfSelectedChars);
return text.Length + newText.Length;
}
else
{
var insert = Keyboard.IsKeyToggled(Key.Insert);
return insert && caretIndex < text.Length ? text.Length : text.Length + newText.Length;
}
}
}
下面是相关的视图代码:
<TextBox MaxLength="50" TextWrapping="Wrap" MaxWidth="150" Margin="4"
Text="{Binding Path=FileNameToPublish}" >
<interactivity:Interaction.Behaviors>
<v:AllowableCharactersTextBoxBehavior RegularExpression="^[0-9.\-]+$" MaxLength="50" />
</interactivity:Interaction.Behaviors>
</TextBox>
PreviewTextInput += (s, e) =>
{
e.Handled = !e.Text.All(char.IsDigit);
};
最好和最优雅的解决方案,只允许整数在文本框(甚至在某些范围)是:
XAML:
<TextBox PreviewTextInput="ValidationTextBox" TextChanged="TextBox_TextChanged"/>
C#:
private void ValidationTextBox(object sender, TextCompositionEventArgs e)
{
int max = 100;
//do not allow futher incorrect typing
e.Handled = !(int.TryParse(((TextBox)sender).Text + e.Text, out int i) && i >= 1 && i <= max);
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
int max = 100;
if (!int.TryParse(((TextBox)sender).Text, out int j) || j < 1 || j > max)
{
//delete incoret input
((TextBox)sender).Text = "";
}
else
{
//delete leading zeros
((TextBox)sender).Text = j.ToString();
}
}
你可以调整最小和最大可接受的数字与max (min)通过开关((TextBox)sender). name。
此解决方案不允许输入的前导零或复制粘贴。在每个场景中,文本框中都有一个正确的数字。