C# WPF和文本格式的文本框
我正在尝试创建一个文本框控件,并强制用户只输入specyfic格式的数字 我怎样才能在WPF中做到这一点 我没有在TextBox类中找到任何类似“TextFormat”或“Format”的属性 我制作了如下文本框(不是在visual editor中):C# WPF和文本格式的文本框,c#,wpf,textbox,C#,Wpf,Textbox,我正在尝试创建一个文本框控件,并强制用户只输入specyfic格式的数字 我怎样才能在WPF中做到这一点 我没有在TextBox类中找到任何类似“TextFormat”或“Format”的属性 我制作了如下文本框(不是在visual editor中): 我希望文本框的行为类似于MS Access表单(例如,用户只能以“000.0”格式在该文本框中输入数字)。根据您的说明,您希望将用户输入限制为带小数点的数字。 您还提到您正在以编程方式创建文本框 使用TextBox.previewtextput
我希望文本框的行为类似于MS Access表单(例如,用户只能以“000.0”格式在该文本框中输入数字)。根据您的说明,您希望将用户输入限制为带小数点的数字。 您还提到您正在以编程方式创建文本框 使用TextBox.previewtextput事件确定字符类型并验证TextBox中的字符串,然后在适当的情况下使用e.Handled取消用户输入 这将实现以下目的:
public MainWindow()
{
InitializeComponent();
TextBox textBox = new TextBox();
textBox.PreviewTextInput += TextBox_PreviewTextInput;
this.SomeCanvas.Children.Add(textBox);
}
进行验证的肉和土豆:
void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// change this for more decimal places after the period
const int maxDecimalLength = 2;
// Let's first make sure the new letter is not illegal
char newChar = char.Parse(e.Text);
if (newChar != '.' && !Char.IsNumber(newChar))
{
e.Handled = true;
return;
}
// combine TextBox current Text with the new character being added
// and split by the period
string text = (sender as TextBox).Text + e.Text;
string[] textParts = text.Split(new char[] { '.' });
// If more than one period, the number is invalid
if (textParts.Length > 2) e.Handled = true;
// validate if period has more than two digits after it
if (textParts.Length == 2 && textParts[1].Length > maxDecimalLength) e.Handled = true;
}
根据您的说明,您希望将用户输入限制为带小数点的数字。 您还提到您正在以编程方式创建文本框 使用TextBox.previewtextput事件确定字符类型并验证TextBox中的字符串,然后在适当的情况下使用e.Handled取消用户输入 这将实现以下目的:
public MainWindow()
{
InitializeComponent();
TextBox textBox = new TextBox();
textBox.PreviewTextInput += TextBox_PreviewTextInput;
this.SomeCanvas.Children.Add(textBox);
}
进行验证的肉和土豆:
void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// change this for more decimal places after the period
const int maxDecimalLength = 2;
// Let's first make sure the new letter is not illegal
char newChar = char.Parse(e.Text);
if (newChar != '.' && !Char.IsNumber(newChar))
{
e.Handled = true;
return;
}
// combine TextBox current Text with the new character being added
// and split by the period
string text = (sender as TextBox).Text + e.Text;
string[] textParts = text.Split(new char[] { '.' });
// If more than one period, the number is invalid
if (textParts.Length > 2) e.Handled = true;
// validate if period has more than two digits after it
if (textParts.Length == 2 && textParts[1].Length > maxDecimalLength) e.Handled = true;
}
考虑使用WPF的内置验证技术。请参阅该类的MSDN文档,以及此文档。考虑使用WPF的内置验证技术。请参阅有关该类的MSDN文档,以及这个。您可能需要的是一个屏蔽输入。WPF没有,因此您可以自己实现它(例如,通过使用),或者使用可用的第三方控件之一:
- 您可能需要的是一个屏蔽输入。WPF没有,因此您可以自己实现它(例如,通过使用),或者使用可用的第三方控件之一: